<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by activesludge on Medium]]></title>
        <description><![CDATA[Stories by activesludge on Medium]]></description>
        <link>https://medium.com/@activesludge?source=rss-ff5b1211e6b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m4X0EWWH7U7sDJqVYRpwjg.png</url>
            <title>Stories by activesludge on Medium</title>
            <link>https://medium.com/@activesludge?source=rss-ff5b1211e6b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:48:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@activesludge/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS 18 — Apple's Translation API]]></title>
            <link>https://medium.com/aviv-product-tech-blog/ios-18-apples-translation-api-ea9a5afc281f?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9a5afc281f</guid>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[language]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 09:13:46 GMT</pubDate>
            <atom:updated>2024-11-19T09:13:46.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS 18 — Apple&#39;s Translation API</h3><p>Say goodbye to copy-pasting text between apps!</p><p>With iOS 18, Apple’s new <a href="https://developer.apple.com/documentation/translation">Translation</a> API brings translation seamlessly into the user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*MQg4rQiZQzXgUVKi.jpg" /><figcaption>Illustration by <a href="https://www.freepik.com/author/vectorjuice">vectorjuice</a> at <a href="http://www.freepik.com/">freepik</a></figcaption></figure><p>Users do not have to copy and paste a text from an app to a translation apps anymore. They will be able to translate a text directly within the app elegantly.</p><p>Moreover, they&#39;ll be able to replace any text in the app. This includes any field or label. Sequentially or all at once.</p><p>I’ll walk you through some experiments with this powerful API and showcase a demo app that illustrates how some made up real-world scenarios can benefit from these features.</p><p>We can demonstrate the APIs capabilities in three main categories:</p><p><strong>System UI</strong></p><p>Using Apple native tools to translate text in Translation in-app popup and optionally replace the original text in the app.</p><ul><li>Overlay Translation</li><li>Replace Translation</li></ul><p><strong>Custom UI</strong></p><p>Translate a text or a batch of those and tailor your UI as you see fit.</p><ul><li>Single String</li><li>Batch of Strings</li><li>Batch as a sequence</li></ul><p><strong>Availability</strong></p><p>Checks the availability of translations based on user preferences, device settings, and installed language packs.</p><ul><li>Language availability</li><li>Prepare for Translation</li></ul><p>Plus, I&#39;ll share with you what you should expect and what I encountered unexpectedly.</p><p>Let&#39;s jump in.</p><h3>Requirements</h3><ul><li>A real device (Translation API is not supported on simulated devices. Also not on Preview)</li><li>iOS 18.0 +</li><li>Xcode 16.0 +</li><li>Apple&#39;s Translate app has to be installed on the device. Since iOS 14, it&#39;s installed automatically.</li></ul><h3>Demo project</h3><p>Here you can download the demo app and run it on Xcode.</p><p>Features are developed using both just a view and with a view model to provide flexibility on implementation.</p><p><a href="https://github.com/Aviv-public/apples-translation-api-demo">https://github.com/Aviv-public/apples-translation-api-demo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_pOy2rm5cM2uEwSsKeFCWQ.gif" /><figcaption>Translation API Demo</figcaption></figure><h3>System UI</h3><h4>Overlay Translation</h4><ul><li>Opens an overlay of Apple’s Translate app within our app.</li><li>Just like copying and pasting a text to the Translate app.</li><li>User can pick any source and target language they want in the overlay sheet.</li></ul><p>In this example, we showcase a legal disclaimer page. Let&#39;s pretend that, to comply with local law, the particular disclaimer below must be displayed in the local language. However, to simplify the experience for our international users, we also offer a convenient button that provides a quick translation, allowing users to easily understand the content in their preferred language</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*bc--rgY4NCM5b3WKIeLiLQ.gif" /><figcaption>A legal disclaimer page that must be presented in German, due to legal reasons.</figcaption></figure><pre><br>struct LegalDisclaimerDemoView: View {<br>    let legalTextTitle = &quot;Nutzungsbedingungen&quot;<br>    let legalText = &quot;Diese App dient ausschließlich ...&quot;<br><br>    var textToBeTranslated: String {<br>        legalTextTitle + &quot;\n&quot; + legalText<br>    }<br><br>    @State var isTranslationOverlayPresented = false<br><br>    var body: some View {<br>        ...<br><br>        Text(verbatim: legalText)<br>            // Presents the sheet binding it to a boolean <br>            // just like presenting a sheet<br>            // Add the source String as the text argument.<br>            .translationPresentation(<br>                isPresented: $isTranslationOverlayPresented,<br>                text: textToBeTranslated<br>            )<br><br>        ...<br>        .overlay(alignment: .topTrailing) {<br>            Button {<br>                // Show translate overlay<br>                isTranslationOverlayPresented = true<br>            } label: {<br>                Image(systemName: &quot;translate&quot;)<br>            }<br>        }<br>        ...<br>    }<br>}</pre><h4>Replace Translation</h4><ul><li>Opens an overlay of Apple’s Translate app within our app. Same as the prior feature.</li><li>User can pick any source and target language they want in the overlay sheet.</li><li>Now presents an option called “Replace with Translation” to replace the text within the app.</li><li>Replacing the translated String is up to the developer.</li></ul><p>In this example, we present a real estate property detail page. The description was filled in French by the seller. We provide a button to see a translation of this description, and elegantly replace it inside of our app. Notice how the description turns into English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*JfO5kS0a5XJ9RmneeXULkQ.gif" /><figcaption>A real estate property detail page with a description that has been filled in French.</figcaption></figure><pre>struct PropertyDetailDemoView: View {<br>    ...<br><br>    @State private var isTranslationOverlayPresented = false<br><br>    var body: some View {<br>        ...<br>        .translationPresentation(<br>            isPresented: $isTranslationOverlayPresented,<br>            text: viewModel.property.description<br>        ) { translatedText in<br>            ...<br>            // Replace the translatedText here<br>            viewModel.propertyDescription = translatedText<br>        }<br>        ... <br>        Button {<br>            isTranslationOverlayPresented = true<br>        } label: {<br>            Image(systemName: &quot;translate&quot;)<br>        }<br>    }<br>}</pre><h3>Custom UI</h3><p>Doesn’t present and overlay view from the system. User doesn’t have to leave the app. We have the ultimate freedom to display translations.</p><ul><li>It’s up to developer to display the translation.</li><li>It’s technically a Task. Which means it’s asynchronous. Has a delay, and can fail.</li></ul><p>The API works with a couple of extra objects:</p><p>TranslationSession</p><ul><li>A class that performs translations between a pair of languages.</li><li>It uses a configuration to define the source and target languages.</li><li>We obtain an instance of this class inside the closure by adding the view modifier .translationTask(_:action:) to a SwiftUI view.</li><li>It contains the methods we need to translate a source text.</li><li>All translations using the TranslationSession class are processed on the user’s device. Apple may collect API usage and performance metrics including the app bundle ID and the original and translated language, but this data does not include the original or translated content.</li></ul><p>TranslationSession.Configuration</p><ul><li>Specifies the source and target languages to use in a translation session. Default initialisation allows system to detect source and target language automatically.</li><li>When you pass this configuration into the .translationTask(_:action:) function, the framework uses the configuration you initialised for the translation.</li></ul><p>Locale.Language</p><ul><li>A type that represents a language, as used in a locale.</li></ul><h4>Single String</h4><ul><li>Pass the text and receive a response that contains translated text.</li></ul><p>Here, we have a contact form to reach out to a seller. The user wrote their message in English. We give them a kind reminder saying that the seller of the property is from Italy. Sending the message in Italian may help them in their effort to get the best deal. They see the translation in a sheet, if they use it, the app replaces the message with the translated one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*meAe6019VE4nqxplrrlThA.gif" /><figcaption>A contact form to reach out to a property seller. The page offers the user to translate their message to Italian.</figcaption></figure><pre>struct ContactSellerView: View {<br>    ...<br>    @State private var message: String =<br>    &quot;&quot;&quot;<br>    Hello, <br>    I&#39;m interested in your property. I like what you did with the interior design. I love the neighborhood and the location. But I&#39;m looking for an at least 10% discount on the deal. Is it acceptable to you? Please let me know. <br>    Thanks!<br>    &quot;&quot;&quot;<br>    ...<br><br>    @State private var configuration: TranslationSession.Configuration?<br>    @State private var translatedMessage: String = &quot;&quot;<br>    @State private var isTranslationSheetPresent: Bool = false<br><br>    var body: some View {<br>        ...<br><br>        Button {<br>            triggerTranslation()<br>        } label: {<br>            HStack {<br>                Text(&quot;See how it looks in 🇮🇹&quot;)<br>            }<br>        }<br>        // Once the configuration property detects a change, <br>        // it triggers a new session. <br>        .translationTask(configuration) { session in<br>            do {<br>                // Use the session the task provides to translate the text.<br>                let response = try await session.translate(message)<br>                // Update the view with the translated result.<br>                translatedMessage = response.targetText<br>                isTranslationSheetPresent = true<br>            } catch {<br>                // Handle any errors.<br>            }<br>        }<br>        ...<br>    }<br><br>    private func triggerTranslation() {<br>        guard configuration == nil else {<br>            // Call .invalidate() method to trigger the translation again <br>            // with the same configuration instance<br>            configuration?.invalidate()<br>            return<br>        }<br><br>        // Create a new configuration for the translation session.<br>        // This configuration will target Italian as the target language.<br>        configuration = .init(target: .init(identifier: &quot;it&quot;))<br>    }<br>}</pre><h4>Batch of Strings</h4><ul><li>Send an array of String in order, receive an array of translated String in the same order.</li></ul><p>Here&#39;s a survey for a property detail page. The real estate agency is curious about how satisfied was the interested party about the details. The survey statements were provided by the agent, so they are in Dutch. We provide them a way to translate all those statements. Once the user taps on the translate button, all statements turn into the language of users location, in this case German.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*mY8SsRdsIR1wtNTD2Ozcxg.gif" /><figcaption>Property detail survey in Dutch.</figcaption></figure><pre>import SwiftUI<br>import Translation<br><br>struct SurveyPageView: View {<br>    // Statement about the satisfaction on the property detail page in Dutch<br>    @State var statements = [<br>        &quot;De details van het eigendom waren duidelijk.&quot;,<br>        &quot;De foto’s van het eigendom waren van goede kwaliteit.&quot;,<br>        ...<br>    ]<br><br>    @State private var configuration: TranslationSession.Configuration?<br><br>    var body: some View {<br>            ...<br><br>            Button {<br>                triggerTranslation()<br>            } label: {<br>                Image(systemName: &quot;translate&quot;)<br>            }<br><br>            ...<br><br>            .translationTask(configuration) { session in<br>                await translateAllAtOnce(using: session)<br>            }<br><br>            ...<br>        }<br>    }<br><br>    ...<br><br>    private func triggerTranslation() {<br>        guard configuration == nil else {<br>            configuration?.invalidate()<br>            return<br>        }<br><br>        // Default initializer allows device to detect the source language <br>        // and the target language.<br>        // Target language is based on user&#39;s region by default.<br>        configuration = .init()<br>    }<br><br>    private func translateAllAtOnce(using session: TranslationSession) async {<br>        // Translate all statements at once<br>        Task { @MainActor in<br>            let requests: [TranslationSession.Request] = statements.map {<br>                // Map each item into a request.<br>                TranslationSession.Request(sourceText: $0)<br>            }<br><br>            do {<br>                let responses = try await session.translations(from: requests)<br>                withAnimation {<br>                    statements = responses.map {<br>                        // Update each item with the translated result.<br>                        $0.targetText<br>                    }<br><br>                    ...<br>                }<br>            } catch {<br>                // Handle any errors.<br>            }<br>        }<br>    }<br>}<br></pre><h4>Batch as a sequence</h4><ul><li>An array of “translation requests” can be send sequentially. Then the result can be processed as they are being received.</li><li>Order of receiving is not guaranteed. But can be tracked with index using clientIdentifier property.</li><li>Can be useful for translating a set of very large texts.</li></ul><p>Here we have an agents page and reviews given by customers. They&#39;re in French. When the blue button is tapped, we translate every review one by one to the primary language, which is German. When it&#39;s tapped again they&#39;re translated into English. which is the second preferred language of user&#39;s device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*0n5FdkREMsQQ0eMufXGTuw.gif" /><figcaption>An agents reviews in French. They’re being translated into German, then English.</figcaption></figure><pre>struct RealEstateAgentProfileView: View {<br>    ...<br>    // Customer reviews with dates and reviewer names<br>    @State var reviews: [Review] = .reviews<br><br>    ...<br><br>    @State private var configuration: TranslationSession.Configuration?<br><br>    var body: some View {<br>        ...<br>        Button {<br>            triggerTranslation()<br>        } label: {<br>            Image(systemName: &quot;translate&quot;)<br>        }<br>        ...<br>        .translationTask(configuration) { session in<br>            await translateSequence(session)<br>        }<br>        ...<br>    }<br><br>    private func triggerTranslation() {<br>        guard configuration == nil else {<br>            configuration?.invalidate()<br>            return<br>        }<br><br>        // In default, source language will be detected as French<br>        // since the review texts are in French.<br>        // Target language is user&#39;s region, in this case German.<br>        // When same configuration is used, then the source language is German,<br>        // and the target language will the user&#39;s prefered language, <br>        // in this case English.<br>        configuration = .init()<br>    }<br><br>    private func translateSequence(_ session: TranslationSession) async {<br>        Task { @MainActor in<br>            // Create an array of requests. Use the index of the review array <br>            // as the client identifier.<br>            let requests: [TranslationSession.Request] =  reviews.enumerated().map { (index, review) in<br>                .init(sourceText: review.text, clientIdentifier: &quot;\(index)&quot;)<br>            }<br><br>            do {<br>                // Translate the batch of requests.<br>                // For each response received, update the corresponding review in the array.<br>                for try await response in session.translate(batch: requests) {<br>                    guard let index = Int(response.clientIdentifier ?? &quot;&quot;) else { continue }<br>                    withAnimation {<br>                        // The client identifier is used to match the response to the original reviews<br>                        reviews[index].text = response.targetText<br>                    }<br>                }<br>            } catch {<br>                // Handle error<br>            }<br>        }<br>    }<br>}</pre><h3>Availability</h3><h4>Available languages</h4><p>You can see the availability of languages the API offers. LanguageAvailability().status(_ from: _to:) checks to see if a specific language pairing is installed and ready for translation.</p><ul><li>.installed supports, has been downloaded and made ready for use in a translation.</li><li>.supported supports but can’t yet use. Only after it downloads and installs.</li><li>.unsupported doesn’t support.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*mT4i8HlVGz0WsP0WBIt2qA.gif" /><figcaption>A page that displays the availability of a language pairing.</figcaption></figure><pre>@Observable<br>class LanguageAvailabilityViewModel {<br>    var isTranslationSupported: Bool?<br>    ...<br><br>    func checkLanguageSupport(from source: Locale.Language, to target: Locale.Language) async {<br>        let availability = LanguageAvailability()<br>        let status = await availability.status(from: source, to: target)<br><br>        switch status {<br>        case .installed, .supported:<br>            isTranslationSupported = true<br>        case .unsupported:<br>            isTranslationSupported = false<br>        @unknown default:<br>            print(&quot;Not supported&quot;)<br>        }<br>    }<br>}</pre><h4>Prepare languages</h4><ul><li>Displays a sheet asking the user’s permission to start downloading the language pairing. So that the above translation features can be ready from the get going.</li><li>Useful to prepare the device for translations.</li><li>If user is faced with any of above features before their device has the necessary language packs, the device will automatically ask to download languages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*CZ2ixzSmrSYa1KUyJ9k8-A.gif" /><figcaption>A page where user can prepare the device for In-App translations.</figcaption></figure><pre>struct PrepareTranslationView: View {<br>    @State private var configuration = TranslationSession.Configuration(<br>        source: Locale.Language(identifier: &quot;pt_BR&quot;),<br>        target: Locale.Language(identifier: &quot;ko_KR&quot;)<br>    )<br><br>    @State private var buttonTapped = false<br><br>    var body: some View {<br>        ...<br>        Button(<br>            action: {<br>                configuration.invalidate()<br>                buttonTapped = true<br>            }<br>        ) {<br>            Text(&quot;Download language packs&quot;)<br>        ...<br>        }<br>        ...<br>        .translationTask(configuration) { session in<br>            if buttonTapped {<br>                do {<br>                    // This will present the sheet to <br>                    // download the required language packs.<br>                    try await session.prepareTranslation()<br>                } catch {<br>                    // Handle any errors.<br>                }<br>            }<br>        }<br>        ..<br>    }<br>    ...<br>}</pre><h3>In default configuration, …</h3><ul><li>If the language of the source text is detected to be the user&#39;s <strong>region</strong>, then the target defaults to <strong>device’s preferred language</strong>.</li><li>If the source is not the same with the region, the target defaults to the <strong>region’s language</strong>.</li><li>If the source and target language pairing isn’t available on the device, user will be prompted with an overlay asking to download it.</li><li>If the translation intend is unclear from the APIs perspective, user will be prompted with an overlay asking to pick a source language from the list.</li></ul><h3>It was unexpected when I saw, that …</h3><ul><li>When the Translate app isn&#39;t installed on the device, features do not work as expected. For instance, when you try to use Custom UI features, the API throws error. But System UI features work just fine. So, Translate app is better be installed on user&#39;s device, or you may face with unexpected behaviours.</li><li>There is no way to check beforehand, whether the user has the Translation app on their device or not.</li><li>In default, if the target isn&#39;t specified in the configuration, target language is set to the device&#39;s region. I would expect it to be the devices preferred language, which wasn&#39;t the case.</li></ul><h3>User&#39;s Permission …</h3><p>Is required by Apple’s Translate app (not the app utilising the Translation API) for the first time:</p><ul><li>to read user input for translations, and</li><li>to download source and target language when translation is being used.</li></ul><h3>Advantages</h3><ul><li>Translates any text in the app.</li><li>Very easy to use and implement.</li><li>Translation are done on device. So, it&#39;s more secure and apart from downloading language pairings does not require constant internet connection.</li><li>You can expand and limit available languages in your app.</li><li>A large set of language availability.</li><li>Emojis do not distract translations.</li><li>Apple’s own API. Support in future is pretty much guaranteed.</li><li>Already downloaded languages can be present in the device and can be utilised by the API.</li><li>The API is smart enough to determine source and target languages, if a specific configuration isn’t passed as an argument.</li></ul><h3>Disadvantages</h3><ul><li>Can redirect user out of your apps.</li><li>Translations are provided by Apple. No any other translation API can be injected.</li><li>The algorithm of the translation is a black box. You will have no control over the translated text. They can get wrong.</li><li>Only available after iOS 18. No backward availability.</li><li>Internet connection is required for the first usage. Language pairings have to be downloaded.</li><li>Custom UI features do not work without the Translate app.</li></ul><h3>Conclusion</h3><p>Easy to implement. Definitely an easy win for any text in your apps that get translated frequently by users. This can be a great addition to any app.</p><p>I hope that this article will be useful to you.</p><p>Have a great one, cheers! ✌️</p><h4>References:</h4><ul><li><a href="https://developer.apple.com/videos/play/wwdc2024/10117/">Meet the Translation API — WWDC24 — Videos — Apple Developer</a></li><li><a href="https://developer.apple.com/documentation/translation/translating-text-within-your-app">Translating text within your app | Apple Developer Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9a5afc281f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aviv-product-tech-blog/ios-18-apples-translation-api-ea9a5afc281f">iOS 18 — Apple&#39;s Translation API</a> was originally published in <a href="https://medium.com/aviv-product-tech-blog">AVIV Product &amp; Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher-Order Reducers with KeyPath and CaseKeyPath in the Composable Architecture]]></title>
            <link>https://medium.com/aviv-product-tech-blog/higher-order-reducers-with-keypath-and-casekeypath-in-the-composable-architecture-2c0ddfd4239d?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c0ddfd4239d</guid>
            <category><![CDATA[keypath]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Tue, 21 May 2024 08:01:36 GMT</pubDate>
            <atom:updated>2024-05-27T14:17:26.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Expand your arsenal with this technique to take your app&#39;s capabilities one step further</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E7tCQRxQ5zHLmi16.jpg" /><figcaption>A scene from the iconic movie Matrix (1999) where Neo was finally starts to feel he&#39;s the chosen one. This image visualises how I personally felt when I grasped the concept of KeyPath in Swift language for the first time.</figcaption></figure><p>Before we dive into the intricacies of reusable reducers, it’s important to note that this article is tailored for readers who already have a good understanding of <a href="https://github.com/pointfreeco/swift-composable-architecture">the Composable Architecture (TCA)</a>. If you’re new to this framework/architecture, you may find it beneficial to familiarise yourself with it before proceeding.</p><h3>When do we use the Higher-Order Reducers?</h3><p>When we want to extract a common logic across actions, we create a private function and use that method. But, what about common logic across features?</p><p>My first intuition would be to create a dependency that has a name like “SomethingManager”, or “SomethingDoer” whose method takes the necessary arguments, then achives the desired objective, possibly returns a type. And that seems perfectly fine. But, I don&#39;t ever see myself overriding this dependency in testing, preview or any other environment, so a dependency feels like an overkill here. So, is there any other alternative?</p><p>By taking the inspiration from BindingReducer in TCA framework, I want to show you how you can create a <strong>Higher-Order Reducer</strong> that is sharable across any domain. This will take our reducer&#39;s capabilities one step further.</p><h3>A real world case</h3><p>An actual requirement urged us to find a solution with a custom Higher-Order Reducer. One of our form pages in our app has many fields where we need to validate each field with each keystroke and also with the submit action. We find the most optimal solution by intercepting the binding actions and a submit action that parent reducer uses, then finally do the validation and return error messages if needed. Now we are able to use this validation reducer in any other form that needs it!</p><h3>What&#39;s the objective?</h3><p>We are going to:</p><ul><li>Create a reducer that can intercept certain actions, and mutate the parent&#39;s state,</li><li>make it so that the reducer is reusable in any other feature,</li><li>move any logic from the parent reducer into the Higher-Order Reducer that was otherwise bound to the feature.</li></ul><p>In this article, we are also going to utilise KeyPaths from Swift and CaseKeyPaths from TCA.</p><p>In the end, the body inside our feature&#39;s reducer will look like this:</p><pre>@Reducer<br>struct FeatureReducer {<br>  ...<br><br>    var body: some ReducerOf&lt;Self&gt; {<br>      ...<br>  <br>      HigherOrderReducer(<br>        input: \.someProperty,<br>        output: \.someOtherProperty,<br>        triggerAction: \.someAction<br>      )<br>      <br>      ...<br>    }<br>  <br>  ...<br>}</pre><p>If that&#39;s something you&#39;re interested, let&#39;s refresh our memory by covering some bases first.</p><h3>KeyPaths</h3><p>KeyPaths offer a flexible and type-safe mechanism for working with <strong>properties</strong>, whether accessing them directly, using them as parameters in functions.</p><p>To put it in simpler words, you define KeyPaths by saying “Here’s a key where I expect a property, from a certain type, that returns a certain type”. You can write onto or read from these properties.</p><p>\Root.someProperty, \.id , \.self , etc.</p><p>KeyPaths are already being used extensively by Swift and SwiftUI. You may remember them from ForEach view where you provide a KeyPath for id argument.</p><pre>ForEach(<br>  _ data: Data, <br>  id: KeyPath&lt;Data.Element, ID&gt;, <br>  content: @escaping (Data.Element) -&gt; Content<br>)</pre><p>Plus, this concept is gaining more popularity. It’s definitely worth mastering in order to advance in Swift language.</p><p>More information on that can be found below links:</p><ul><li><a href="https://developer.apple.com/documentation/swift/keypath">KeyPath</a> by Apple</li><li><a href="https://www.swiftbysundell.com/articles/the-power-of-key-paths-in-swift">The power of KeyPaths in Swift</a> by Sundell</li></ul><h3>CaseKeyPaths</h3><p>Unfortunately, a structure like KeyPath did not exist for enum cases where we want pass actions which are exclusively enums. Not until, a new concept is introduced by TCA developers to address the missing part. It&#39;s called CaseKeyPath from <strong>CasePaths</strong> library by <strong>PointFree</strong>. It allows us to pass enum cases just like KeyPaths. It looks like this:</p><p>\.view.didTapButton</p><p>Delicious!</p><p>More information on <strong>CaseKeyPaths</strong> can be found below:</p><ul><li><a href="https://github.com/pointfreeco/swift-case-paths">SwiftCasePaths</a> by PointFree</li></ul><h4>Fun fact</h4><p>Here&#39;s what a <strong>CasePath</strong> looked like before the introduction of <strong>CaseKeyPath</strong>.</p><p>/Action.view.didTapButton</p><p>In order to pass a CasePath like the above the initialiser had to look like this:</p><pre>init(toViewAction: @escaping (Action) -&gt; ViewAction?) {<br>  self.toViewAction = toViewAction<br>}</pre><p>It was essentially a closure where it takes parent action as argument and expects to return another action. As of today, this is how the framework still works behind the counter. But it seems this usage is bound to be deprecated.</p><h3>Higher-Order Reducer</h3><p>In Swift, “higher order” typically refers to functions or closures that either accept other functions/closures as parameters, or return functions/closures as output. These higher-order functions allow for more flexibility and composability in code, as they can manipulate or encapsulate behaviour.</p><p>In earlier days (mid-2019), that was exactly what it looked like in TCA as well. It meant a reducer function that returns a reducer function.</p><pre>func higherOrderReducer(<br>  _ reducer: @escaping (inout AppState, AppAction) -&gt; Void<br>) -&gt; (inout AppState, AppAction) -&gt; Void {<br><br>  return { state, action in<br>    // do some computations with state and action<br>    reducer(&amp;state, action)<br>    // inspect what happened to state?<br>  }<br>}</pre><p>Over years of transformation, in TCA context, it refers to reducers that are shareable, reusable, can handle an objective, and can be built on top of our apps. One of the most important example is the BindingReducer().</p><h3>How would Higher-Order Reducers help us?</h3><h4>Managing complexity</h4><p>In large applications, managing state and actions can get really complex. They help address this problem by allowing you to break down the state management logic into smaller, more manageable units. This makes it easier to understand, maintain, and modify the codebase as your application grows.</p><h4>Reusability</h4><p>They enable you to encapsulate common patterns or behaviours within reusable bodies. This promotes code reuse across different parts of your application, reducing duplication and ensuring consistency in how state is managed.</p><h4>Testing</h4><p>You can write unit tests for individual reducers. By this way we can ensure that each piece of state management logic behaves as expected in isolation.</p><h3>Tutorial</h3><h4>Project Setup</h4><p>Create a new project using Xcode. Minimum requirements for this project is as below:</p><ul><li>Xcode 15.3</li><li>Swift 5.9</li><li>Minimum deployment target: iOS 17.0</li><li><a href="https://github.com/pointfreeco/swift-composable-architecture">TCA</a>: 1.10.0</li></ul><p>Once packages are resolved. Give it a run. You may be asked to enable macros by Xcode. Go ahead and enable them. Then we&#39;re good to go.</p><h4>User story</h4><p>I have come up with a user story for us to start exercising. It’s just a fictional one to keep things as simple as possible for us to step into the concept.</p><blockquote>I want to be able to enter a text into a field. When I tap onto the button, I want to see that same text in uppercased form below. I want to be able to long press and copy the uppercased text. This logic has to be reusable. We’ll call this feature <strong>Shouting text</strong>.</blockquote><p>The logic is to take a <strong>string as input </strong>and return an <strong>uppercased string as output </strong>after a certain <strong>trigger action</strong>.</p><h4>Shouting text</h4><p>First, create a reducer for our feature. Name it ShoutingText.swift . Copy and paste below code to this file.</p><pre>import ComposableArchitecture<br><br>@Reducer<br>struct ShoutingText {<br>    @ObservableState<br>    struct State {<br>        var text: String = &quot;&quot;<br>        var uppercasedText: String = &quot;&quot;<br>    }<br>    <br>    enum Action: BindableAction {<br>        case didTapShoutButton<br>        case binding(BindingAction&lt;State&gt;)<br>    }<br>    <br>    var body: some ReducerOf&lt;Self&gt; {<br>        BindingReducer()<br><br>        Reduce { state, action in<br>            switch action {<br>            case .didTapShoutButton:<br>                // Here&#39;s the state mutating logic that<br>                // we want to move to the new reducer.<br>                state.uppercasedText = state.text.uppercased()<br>                return .none<br>            case .binding:<br>                return .none<br>            }<br>        }<br>    }<br>}</pre><p>Second, create a new file called ShoutingTextView.swift then copy and paste below code inside.</p><pre>import ComposableArchitecture<br>import SwiftUI<br><br>struct ShoutingTextView: View {<br>    @Bindable var store: StoreOf&lt;ShoutingText&gt;<br>    <br>    var body: some View {<br>        Form {<br>            Section {<br>                TextField(<br>                    &quot;what do you mean&quot;,<br>                    text: $store.text<br>                )<br>                .textFieldStyle(.plain)<br><br>                Button {<br>                    store.send(.didTapShoutButton)<br>                } label: {<br>                    Image(systemName: &quot;person.wave.2.fill&quot;)<br>                }<br>            }<br><br>            Text(store.uppercasedText)<br>                .textSelection(.enabled)<br>        }<br>        .navigationTitle(&quot;Shout it!&quot;)<br>    }<br>}<br><br>#Preview {<br>    NavigationStack {<br>        ShoutingTextView(<br>            store: Store(<br>                initialState: ShoutingText.State(),<br>                reducer: ShoutingText.init<br>            )<br>        )<br>    }<br>}</pre><p>When you run the preview you should see a screen like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*zxPvl3gui90DDhde1FLmIA.png" /><figcaption>&quot;Shout it!&quot; preview on canvas</figcaption></figure><p>Try and type something to the text field and tap onto the button below. See the text being uppercased.</p><p>If everything is in order, it means our base code is ready.</p><h3>Creating a Higher-Order Reducer</h3><p>These are not so different from typical feature reducers. They just don&#39;t have to possess a <em>State</em> struct and an <em>Action</em> enum.</p><p>Create a new file called UppercasedReducer.swift, then copy and paste below code inside.</p><pre>import ComposableArchitecture<br><br>// 1<br>@Reducer<br>struct UppercasedReducer&lt;State, Action, UppercaseAction&gt; where Action: CasePathable {<br>    // 2<br>    private let keyPathToText: KeyPath&lt;State, String&gt;<br>    private let keyPathToUppercasedText: WritableKeyPath&lt;State, String&gt;<br>    private let caseKeyPathToAction: CaseKeyPath&lt;Action, UppercaseAction&gt;<br><br>    init(<br>        input keyPathToText: KeyPath&lt;State, String&gt;,<br>        output keyPathToUppercasedText: WritableKeyPath&lt;State, String&gt;,<br>        triggerAction caseKeyPathToAction: CaseKeyPath&lt;Action, UppercaseAction&gt;<br>    ) {<br>        self.keyPathToText = keyPathToText<br>        self.keyPathToUppercasedText = keyPathToUppercasedText<br>        self.caseKeyPathToAction = caseKeyPathToAction<br>    }<br><br>    // 3<br>    func reduce(into state: inout State, action: Action) -&gt; Effect&lt;Action&gt; {<br>        if action[case: caseKeyPathToAction] != nil {<br>            state[keyPath: keyPathToUppercasedText] = state[keyPath: keyPathToText].uppercased()<br>        }<br>        return .none<br>    }<br>}</pre><p>Let&#39;s see what&#39;s happening here:</p><ol><li>UppercasedReducer is the Reducer that will do the job. Thanks to @Reducer macro, we&#39;re free from filling in some boilerplate code, such as conformances. <br>Plus, it&#39;s generic. Which mean its properties will be inferred by the types of properties from whichever Reducer uses it when initialised.<br>State is the parent state. Action is the parent action. UppercaseAction is the sub action of the parent action we want to intercept and mutate the state with.<br>In order to take advantage of CaseKeyPaths, the Action generic parameter has to conform to CasePathable protocol.</li><li>keyPathToText is a <strong>KeyPath</strong> to the text we want to turn into uppercase. It&#39;s read only. The root is the parent state and the value is a String.<br>keyPathToUppercasedText is a <strong>WritableKeyPath</strong> to the final text we want to display on the screen. It&#39;s needs to be writable because we have to replace what&#39;s there after mutation. The root is the parent state and the value is a String.<br>caseKeyPathToAcion is a <strong>CaseKeyPath</strong> to the action we want to intercept and make the state mutation. The root is the parent action and the value is an enum case of that action.</li><li>Here&#39;s the reduce function that will do the mutation. We employ an if statement to determine if the action that is subscripted with the caseKeyPathToAction is not nil. This serves as our interception mechanism for actions. <br>If the condition holds true, we proceed to replace the property referenced by keyPathToUppercasedText in the parent state with the property referenced by keyPathToText within the same parent, right after applying the .uppercased() method. Subsequently, we conclude the operation by returning the .none effect.</li></ol><h3>Usage of the Higher-Order Reducer</h3><p>Return to ShoutingText.swift file and initialise the our new UppercasedReducer inside the body. Since we have no particular side effect to run, go ahead and remove the other Reduce initialiser.</p><pre>import ComposableArchitecture<br><br>@Reducer<br>struct ShoutingText {<br>    ...<br>    <br>    var body: some ReducerOf&lt;Self&gt; {<br>        BindingReducer()<br><br>        UppercasedReducer(<br>            input: \.text,<br>            output: \.uppercasedText,<br>            triggerAction: \.didTapShoutButton<br>        )<br>    }<br>}</pre><p>Thanks to @Reducer macro right above ShoutingText reducer, we don&#39;t have to explicitly conform the Action enum of the feature to CasePathable protocol. It&#39;s already covered! You can expand the macro to see conformances above there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lioe5uvkYPg5Gzy4EyZtDg.png" /><figcaption>@CasePathable macro above Action enum provided by @Reducer macro.</figcaption></figure><p>And that’s it. Run the app and see the reducer is doing its job!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*gTK0IVuw4b7oQ2M826OX8A.gif" /></figure><p>The end product hasn&#39;t changed a bit, but the underlying difference is huge. Now we have a reducer that is easily sharable. We won&#39;t have to repeat this logic anywhere in our code base. Lovely.</p><p>Congratulations on completing the above journey through the exercise using KeyPaths and CaseKeyPaths in the Composable Architecture!</p><p>By following along with this article, you’ve taken a solid step towards developing reusable reducers in your app.</p><p>On top of my mind, here are some examples where Higher-Order Reducer can be useful:</p><ul><li>Logging</li><li>Tracking events</li><li>State property validations, filters, etc.</li></ul><p>Let me know if you can think of any other use case!</p><p>Keep exploring, experimenting, and pushing the boundaries of what’s possible with the Composable Architecture.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c0ddfd4239d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aviv-product-tech-blog/higher-order-reducers-with-keypath-and-casekeypath-in-the-composable-architecture-2c0ddfd4239d">Higher-Order Reducers with KeyPath and CaseKeyPath in the Composable Architecture</a> was originally published in <a href="https://medium.com/aviv-product-tech-blog">AVIV Product &amp; Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facade Design Pattern in Swift for Beginners (with async/await)]]></title>
            <link>https://medium.com/aviv-product-tech-blog/facade-design-pattern-in-swift-for-beginners-with-async-await-b8f751c49d74?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8f751c49d74</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 07:55:16 GMT</pubDate>
            <atom:updated>2023-06-19T07:55:16.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you are visiting a local restaurant. The first thing you think of, should <strong>never</strong> be whether the kitchen has enough potatoes or enough gas to fire the stove, or whether the chef has the ability to cook the dish you want or not.</p><p>That is when the waiters/waitresses come into play. They greet you with a smile, show you where you can sit, give you a simple menu, and even tell you their recommendations or what&#39;s not available. They are the <strong>facade</strong> between you and the complex internal operations in the restaurant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*HbxOkWTcGYGZNwPL" /><figcaption><a href="https://www.freepik.com/free-vector/two-women-sitting-cafe_11235990.htm#query=waitress&amp;position=5&amp;from_view=keyword&amp;track=sph">Image</a> by pch.vector on Freepik</figcaption></figure><p>Similarly, software development can get complicated with many different components to manage. The<strong> Facade design pattern</strong> simplifies the system and provides a straightforward interface for clients to use.</p><p>In this article, we will see how to implement the Facade pattern in Swift with a practical example.</p><h3>Introduction</h3><p>The <strong>Facade Design Pattern </strong>is a <strong>structural </strong>design pattern that provides a simplified interface to a complex system. That <em>should </em>sound familiar right? Since that&#39;s what we do in programming in general…</p><p>We gather independent components from classes, frameworks, and libraries, then provide a simple, meaningful, single answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*ytj2q20Wo3h5UCfEIaIiuw.png" /><figcaption>Facade Design Pattern Diagram</figcaption></figure><p>It consists of three actors:</p><ul><li><strong>Consumer: </strong>Owns and uses the facade object.</li><li><strong>Facade: </strong>Gathers various dependencies around and provides one meaningful method to interact with the system.</li><li><strong>Dependency: </strong>An object that serves a specific purpose in its domain. Each dependency performs a small part of a complex task.</li></ul><h3>When do we use it?</h3><p>Occasionally, it is necessary to obtain appropriate responses from various APIs before initiating any processes. If you find yourself in a position where you need to convert a bunch of responses to a more simple one, <strong>Facade Design Pattern</strong> is what you are looking for.</p><p>Instead of expecting consumers to know each component of the complex system, we can provide a facade to expose the system properly and safely.</p><h3>Code Example</h3><p>We are going to implement an imaginary feature where we order french fries from a waiter at our favorite restaurant. A set of different requirements must be met, in order, before eating them.</p><ol><li>There have to be enough potatoes</li><li>Potatoes have to be prepared by the chef</li><li>A frier will fry them</li><li>The chef will serve them in a basket</li></ol><p>Finally, the waiter will deliver them.</p><p>As we can see, these are quite independent components and actors. They each require different methods to get answers. They each require a different time to complete… It is cruel to expect a customer to know all these and tell the restaurant every time they need french fries, right? Plus, what if they want a burger instead of fries, should they know the steps as well? The answer is no.</p><p>Let&#39;s create a facade for the restaurant, and make the ordering of french fries available to any customer.</p><p>We will take advantage of the async/await feature of Swift as well. Our example will leverage this feature in a serial way. Since each step has to be completed before proceeding to the next step.</p><p>Open up an Xcode playground and start following through the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1228fa62bed7f39fed466a7eb6aebdf5/href">https://medium.com/media/1228fa62bed7f39fed466a7eb6aebdf5/href</a></iframe><p>We have created the Restaurant struct along with the necessary steps to cook a delicious french fry. Each one has its own responsibilities. For simplicity, I have used the Task.Sleep method to simulate the amount of work to be done. Also, all these functions are declared private since we don&#39;t want to disclose our facade&#39;s implementation to the user.</p><p>The async keyword at the end of a function allows the compiler to know that this function can be used in an <strong>asynchronous</strong> context. Either <strong>serially</strong> or <strong>concurrently.</strong></p><p>Now let&#39;s gather all these internal steps and produce a public function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce38cbbe731e12f2ee1f14922842b644/href">https://medium.com/media/ce38cbbe731e12f2ee1f14922842b644/href</a></iframe><p>Here we declared a public function to order a french fry. await keyword before each method call indicates that the program should wait for this method to finish before proceeding.</p><p>Now, let&#39;s see it in action!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2c7ef6e78b456b09a2c95f5a9c336c2/href">https://medium.com/media/f2c7ef6e78b456b09a2c95f5a9c336c2/href</a></iframe><p>The Task keyword here indicates that the closure inside is an asynchronous unit of work. It&#39;s required to use async/await context anywhere in the code.</p><p>If you run, you should see each step progressing and finally serving the french fries. 😋</p><p>Go ahead and experiment on the brand new facade of yours. 🔬🧪</p><p>Now, this is a very limited example of course, where we print simple text. In real life, what you would do is have your dependency methods able to <strong>throw errors</strong>, then the facade can <strong>catch</strong> them and handle each of them accordingly!</p><h4><strong>Challenge</strong></h4><p>Implement the error throwing for each dependency. Follow these steps:</p><ol><li>Create a FrenchFriesErrors. Add types of errors that each step can throw.</li><li>Add throws ability to dependency methods. Plant an error in one of the steps.</li><li>Capture all methods inside the facade in a do block.</li><li>Handle each error in the catch block.</li></ol><p>Try it yourself first.</p><p>Notice that the proceeding steps will not execute after a step throws an error.</p><h4>Solution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8ecc28d57e12555a03c8def70f8d9e2/href">https://medium.com/media/e8ecc28d57e12555a03c8def70f8d9e2/href</a></iframe><p>Congratulations. You’ve made it to the end.</p><p>Now you know what to do if you have to create a complex interface with different dependencies.</p><p>I hope the above explanation makes sense and will be helpful to you on your iOS development journey.</p><p>Have a great one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8f751c49d74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aviv-product-tech-blog/facade-design-pattern-in-swift-for-beginners-with-async-await-b8f751c49d74">Facade Design Pattern in Swift for Beginners (with async/await)</a> was originally published in <a href="https://medium.com/aviv-product-tech-blog">AVIV Product &amp; Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Design Pattern in Swift for Beginners]]></title>
            <link>https://activesludge.medium.com/factory-design-pattern-in-swift-for-beginners-b6d116799033?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d116799033</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 05:45:43 GMT</pubDate>
            <atom:updated>2022-06-01T05:45:43.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*qzk9iDeQq7mFLWzK.jpg" /><figcaption>The Ford assembly line in 1913 by <a href="https://commons.wikimedia.org/wiki/File:Ford_assembly_line_-_1913.jpg">Wikimedia</a></figcaption></figure><p>Programmers can be called a lot of different names, but <strong>artisan </strong>is not one of them, in my opinion. End users, can not feel the difference between two separately initialized buttons.</p><p>We create various buttons, labels, and views. If you find yourself in a position where you copy and paste the same code to create the same objects, this pattern is for you.</p><h3>What is Factory Design Pattern?</h3><p>The factory pattern is a <strong>creational pattern</strong> that allows you to construct things without disclosing the logic that goes into making them. There are usually three actors involved:</p><ol><li>The <strong>owner</strong> of the factory that uses/owns the creation methods</li><li>The <strong>factory </strong>that creates the end object</li><li>The <strong>object</strong> that is the created end product</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*dNsg70xhTM8EwNEWhMFJGg.png" /><figcaption>Factory design pattern diagram</figcaption></figure><p>This design pattern comes in a variety of implementations like the simple factory, the abstract factory, or any others. But each of these, however, has the same purpose which is to encapsulate object creation logic within its class.</p><p>In this article, I will go over the <strong>simple factory</strong> pattern which is better to start for beginners.</p><h3>When do we use it?</h3><p>This pattern comes in handy when:</p><ul><li>You create objects from the same models over and over again,</li><li>Not only creating a particular object but different flavors of the same model according to properties,</li><li>Overall simplifying an object creation,</li><li>Streamlining object creation in projects such as UI components,</li><li>Needing the ability to change all objects all over the project,</li><li>Reducing the if/switch statements inside the view controller.</li></ul><p>Compare below two examples for configuring the ScoreCard model for the score given:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd3b1bbfa578229d1107aa1874dfacec/href">https://medium.com/media/dd3b1bbfa578229d1107aa1874dfacec/href</a></iframe><p>Having all this logic inside our class is eye-soring. If we need to show the scorecard in another place, will I copy this code and paste it there? No.</p><p>By implementing the factory pattern we will end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01a8734ce137359e876de0ea1dbd21fa/href">https://medium.com/media/01a8734ce137359e876de0ea1dbd21fa/href</a></iframe><p>Shorter, cleaner, delicious. The class knows nothing about the creation logic. It&#39;s only concerned with the final object, as it should be.</p><h3>Implementation</h3><p>Fire up a playground and start typing the below code in order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b24f689d65c17f2cf08ecd6c9fff905/href">https://medium.com/media/1b24f689d65c17f2cf08ecd6c9fff905/href</a></iframe><p>We define two structs.</p><ol><li>The first one is the <strong>Score</strong> which we define it with an Int point. And it also provides us with a computed property <strong>status</strong>. The status property will come in handy when differentiating between scores. We won&#39;t be dealing with math in the factory method, because it&#39;s taken care of here.</li><li>The other is <strong>ScoreCard</strong> which we will fill with the information given by the <strong>Score</strong> model.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5004a204a56d829678acfcd607f48bc9/href">https://medium.com/media/5004a204a56d829678acfcd607f48bc9/href</a></iframe><ol><li>Now we created the <strong>ScoreCardFactory</strong> class.</li><li>It has one method for now which takes a <strong>Score</strong> argument and returns a <strong>ScoreCard</strong>.</li><li>Inside the <strong>createScoreCard</strong> method, we create the <strong>ScoreCard</strong> object according to the <strong>status</strong> of the score using the switch case.</li></ol><p>Now, let&#39;s test this new factory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dffb516b7816eb31b8cd39afc97e2c01/href">https://medium.com/media/dffb516b7816eb31b8cd39afc97e2c01/href</a></iframe><ol><li>We defined some scores.</li><li>Initialized the <strong>ScoreCardFactory</strong>.</li><li>Created <strong>ScoreCards</strong> using the factory&#39;s <strong>createScoreCard(for:)</strong> method.</li><li>Printed the result.</li></ol><p>As a result, we built an API for a safe and easy way to create <strong>ScoreCard</strong> objects. In the end, we don&#39;t know how the <strong>ScoreCard</strong> is created. In this class, we are only concerned with the final product.</p><p>Do we need to change how we configure a <strong>ScoreCard</strong>? Now we only need to change one place which is, the factory&#39;s creation method.</p><p>We successfully separated the logic from the owner/user class.</p><h3>A real-world case</h3><p>In the project I work on, we use factory methods for button creation. You see we have predefined buttons which were decided by the design team. And they are going to be the same throughout the app. Now whenever we need to use a button, we don&#39;t create it by ourselves, but initialized a ButtonFactory, then use the create methods which return a button object.</p><p>This factory allows all the developers to use the same method, which prevents misconfiguration.</p><p>A change in the button text font? No problem, just fix it on the factory method. No need to fix it in 25 different locations.</p><h3>Be careful when…</h3><p>All this work may be too much for simple objects. If that&#39;s the case you can put the creation logic directly in the owner/user, which is probably a view controller.</p><p>The key is avoiding repeating ourselves. If you don&#39;t see yourself repeating the same creation logic, it could be fine to not create a factory.</p><p>By the way, if your object takes several stages to construct, the builder pattern may be more appropriate. Check out my article about builder pattern for beginners.</p><p><a href="https://medium.com/swift2go/builder-pattern-in-swift-for-beginners-79415d30872e">Builder Pattern in Swift for Beginners</a></p><p>Congratulations. You’ve made it to the end.</p><p>This is a great pattern to learn and implement. This will be a great asset to your coding arsenal.</p><p>I hope that the above explanation makes sense and will be helpful to you on your iOS development journey.</p><p>Thanks for reading. Have a great one.</p><p>References:</p><ul><li><a href="https://www.raywenderlich.com/">raywenderlich.com</a></li><li><a href="https://refactoring.guru/">refactoring.guru</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d116799033" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern in Swift for Beginners]]></title>
            <link>https://activesludge.medium.com/strategy-design-pattern-in-swift-for-beginners-44cfa93935b4?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/44cfa93935b4</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 11:29:14 GMT</pubDate>
            <atom:updated>2022-04-03T11:29:14.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqoHE0qwHiYw6LjtmL8OvQ.png" /><figcaption><em>Rapp Presenting Prince Repnin-Volkonsky,</em> <a href="https://en.wikipedia.org/wiki/Fran%C3%A7ois_G%C3%A9rard">François Gérard</a></figcaption></figure><p>In order to keep the app’s size as low as possible, we need to reuse components as much as possible. In that sense, UI components come to mind first. So it’s very smart to reuse the UI component if the difference is slight.</p><p>Although I do not hear about it as much as I expected, this pattern is one of the basic patterns in iOS development. I would highly recommend you master it before progressing further in your iOS developer career. And good news, it’s very similar to Delegate Design Pattern in writing.</p><h3>What is Strategy Design Pattern?</h3><p>The strategy pattern specifies a set of interchangeable objects that can be changed or set at runtime. This pattern changes the way the app behaves, so this one is called a <em>behavioral design pattern</em>.</p><p>It consists of:</p><ul><li>One class that owns/uses the strategy. This is usually the View Controller, ViewModel, or whatever manages the logic of the view.</li><li>One protocol dictates what a concrete strategy needs to have</li><li>And any set of concrete strategies that conforms to the above protocol.</li></ul><p>The owner class changes its behaviors according to the given protocol. It doesn’t know which strategy it’s going to implement. It only knows in which field the strategy is going to give it the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*ybLzYWrbopFWi8PGERImYQ.png" /><figcaption>Strategy Design Pattern Diagram</figcaption></figure><h3>When do we use it?</h3><p>If you have two or more behaviors that are interchangeable, a view that you want to reuse and modify during runtime, use this design pattern.</p><p>In another case, if you found yourself making a bunch of if statements to handle various cases in the same view controller, initialize and pass a strategy instead.</p><p>Ultimately the goal is to have a cleaner code that is easier to maintain. Check out two ways to set up the UI below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571fbd9b7b2275f4e3126c3a7694286b/href">https://medium.com/media/571fbd9b7b2275f4e3126c3a7694286b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b3ab84a8e75429fc521edd172d9b07/href">https://medium.com/media/61b3ab84a8e75429fc521edd172d9b07/href</a></iframe><p>The latter one is shorter and seems cleaner.</p><h3>Difference Between Delegate Design Pattern</h3><p>In terms of additional flexibility, this approach is similar to the delegation design pattern in that both rely on a protocol rather than concrete objects. As a result, any object that implements the strategy protocol at runtime can be utilized as a strategy.</p><p>However delegation is more about running functions and passings data through arguments to another class, strategy is about the same class having a variety of usages and behaviors. Delegates are usually decided at runtime. The delegate for a UITableView, for example, can be configured in the view controller or on a storyboard, and they rarely change during runtime. However, at runtime, strategies are meant to be interchangeable.</p><h3>Implementation</h3><p>Start up a playground in Xcode, then start typing the below code.</p><h4>Create the strategy protocol</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbc404a2e89a16aeb1e7706a2bea69b8/href">https://medium.com/media/cbc404a2e89a16aeb1e7706a2bea69b8/href</a></iframe><p>The first thing in order is to define what strategy should conform to. Check what fields you are modifying in your view controller and write the property names for instance.</p><h4><em>Create</em> the concrete strategy classes</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/533fc91302a90e3851e8c0182a453648/href">https://medium.com/media/533fc91302a90e3851e8c0182a453648/href</a></iframe><p>They all conform to the ProductPageStrategy. Every strategy can have its own properties and implementations.</p><h4>Feed the strategy to the owner class</h4><p>Below is the fake ViewController for demonstration purposes. In a real example, it will inherit UIViewController, and have viewDidLoad(). However, it should be formed similar to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/732502b47850700d9c68293d951cbe16/href">https://medium.com/media/732502b47850700d9c68293d951cbe16/href</a></iframe><h4>Test the freshly implemented strategy pattern</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6462f43e1e3839491a513ef9f20270/href">https://medium.com/media/2d6462f43e1e3839491a513ef9f20270/href</a></iframe><p>The first strategy is directly fed to the View Controller inside the init. The others are changed after them since the strategy property is public. You can imagine a button to feed the appropriate strategy during the runtime.</p><p>In the future, we do not need to make a modification to the view controller. If a new user type comes up, we can create a new strategy and feed it outside the view controller.</p><p>The above example is obviously super simple. Imagine a view controller that has a lot of properties, such as images, subtitles, labels, heights, colors, and so on. That&#39;s when this pattern is a lifesaver.</p><h4>A real-world case</h4><p>The last time I used this pattern is for a map view. I was developing a map that annotates where the nearest libraries and cafes are located. Then I needed another map that shows only the libraries and has a segmented control on top of it. I created a strategy protocol with properties &quot;searchType&quot; and &quot;shouldHideSegmentedControl&quot; and then created the concrete strategy object by conforming to the protocol. Finally, feed the strategy when I instantiate the view controller that contains the map view and segmented control. This way, I was able to reuse the same map view controller in multiple cases.</p><h4>Be careful when…</h4><p>If you don&#39;t anticipate further reuse cases for a component, this pattern could be overkill. In particular, it’s OK to place the logic within the consuming view controller or object context if a behavior will never change.</p><p>Congratulations. You’ve made it to the end.</p><p>This is a great pattern to learn and implement. This will be a great asset to your coding arsenal.</p><p>I hope that the above explanation makes sense and will be helpful to you on your iOS development journey.</p><p>Thanks for reading. Have a great one.</p><p>References:</p><ul><li><a href="https://www.raywenderlich.com/">raywenderlich.com</a></li><li><a href="https://refactoring.guru/">refactoring.guru</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44cfa93935b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Pattern in Swift for Beginners]]></title>
            <link>https://activesludge.medium.com/adapter-pattern-in-swift-for-beginners-e5fb0ac73743?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5fb0ac73743</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 07:31:41 GMT</pubDate>
            <atom:updated>2021-09-16T07:31:41.539Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“It is not the strongest of the species that survives, nor the most intelligent. It is the one that is most adaptable to change.”</blockquote><blockquote>-Charles Darwin</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*6AvyxzUpMm-x8X0l" /><figcaption>Image by Jono Dry on <a href="https://www.jonodryart.com/adaption/adaption">Jono Dry Art</a></figcaption></figure><p>As human beings, we know we have to adapt to different environmental conditions. And we are argued to be the best at it, thus we are on top of the food chain. The same ability is also valid for our code. If we want our app to last longer, it should be able to <strong>adapt</strong>.</p><blockquote>The Adapter Pattern is a behavioral design pattern that allows classes that are incompatible to collaborate. Mostly an old legacy class and a new modern class.</blockquote><p>In other sources, it&#39;s also defined as <em>structural design pattern </em>as this pattern combines the capability of two independent interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*yfXq6ODqmAop8MOAe6P0Lw.png" /><figcaption>Adapter Pattern Class Diagram</figcaption></figure><p>It usually consists of four parts:</p><ol><li>An object that uses an adapter is the one that conforms to the adapter protocol.</li><li>The adapter protocol is the one that dictates what the new code should use to adapt to the legacy class.</li><li>An adaptor is developed to pass arguments and calls to the legacy object.</li><li>A legacy class that existed prior to the creation of the protocol and cannot be directly changed to adhere to it.</li></ol><p>An adapter can be created by extending an existing class or by constructing a new adapter class.</p><h3>When do we use it?</h3><p>It’s not always possible to change classes, modules, or functions, especially if they’re from a third-party library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*_2fuWF82g0Eg5Nmd.jpg" /><figcaption>US to EU outlet adapter (converter)</figcaption></figure><p>The most common metaphor to use is an electric adapter. US and EU uses different outlets for their electrical devices. So as someone who lives in US, what do we do when we need to charge our phone when we are visiting EU? We take an adapter with us. So that our foreign charger can communicate with local electrical outlet <strong>safely</strong>.</p><p>A classic use case is a third party login authentication service such as Apple, Google, or Facebook. We definitely do not want to handle three different cases for three different provider. That&#39;s why we create an <strong>adapter</strong> and handle every provider with appropriate adapter class. So that our view controllers can interact with only one interface rather than three.</p><p>Another example is an event service in a mobile app. Our app may have a third party event provider. We don&#39;t want to rely on solely the functions that they provided. We want to be able to control fail cases. There may be a case where the third party library has changed, and we don&#39;t want to be left alone with modifying every single event on our app. That&#39;s why we put an <strong>adapter</strong> between their functions and our view controllers.</p><h4>Implementation</h4><p>Enough talk, let&#39;s make an example using Xcode Playground. Create a new Playground project and follow through.</p><p>For this example, we are going to adapt a 3rd party authentication service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45d3ed5cfe7ba9e6b399bbccc7af681c/href">https://medium.com/media/45d3ed5cfe7ba9e6b399bbccc7af681c/href</a></iframe><p>Imagine ThirdPartyAuthenticator is a third-party class that cannot be modified. Therefore, it is the <strong>legacy object</strong>. For the simplicities sake, we have provided the token directly and pretended like a network call is done without an error. Expect this process to be much more complex and discrete in the real life libraries.</p><p>Ultimately the login function returns a User and an Error.</p><p>Next, add the following code to the end of the playground:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/970e9662bd816baff7cdac8300404af1/href">https://medium.com/media/970e9662bd816baff7cdac8300404af1/href</a></iframe><p>This is the authentication service protocol for our app which acts as the <strong>adapter protocol</strong>. It requires an email and password. If login succeeds, it calls success with a User and Token. Otherwise, it calls failure with an Error.</p><p>Our app will utilise the protocol instead of ThirdPartyAuthenticator directly, and it will gain a leverage by doing that. For example, we will be able to support multiple authentication mechanisms – Apple, Facebook and others – simply by having them all conform to the same protocol. This is the foundation of this design pattern. Isn&#39;t that clever?</p><p>Next, add the following code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d093608a431c5a28c98977f61ef9bc70/href">https://medium.com/media/d093608a431c5a28c98977f61ef9bc70/href</a></iframe><p>We created ThirdPartyAuthenticationAdapter as the <strong>adapter</strong> and conform it to AuthenticationServiceProtocol. Then we created an instance of ThirdPartyAuthenticator . It’s private so that it&#39;s hidden from other classes.</p><p>We added the AuthenticationServiceProtocol login method as required by the protocol. Inside this method, we call ThirdParty libraries login method to get a AuthenticatorUser. If there’s an error, we call failure with it. Otherwise, we create user and token from the authenticatorUser and call success.</p><p>The ThirdPartyAuthenticator is now being enclosed inside the adapter, so that the end consumers don’t need to interact with ThirdPartyAuthenticator&#39;s API directly. This protects against future changes and possible failures. For example, if the Third Party Authenticator ever change their API and it will broke the app. But with the adapter class we only need to fix it here.</p><p>Continue with adding the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8946f1e7199152f2a5980a466f71dd72/href">https://medium.com/media/8946f1e7199152f2a5980a466f71dd72/href</a></iframe><p>For LoginViewController, we first created a new class. It has an authService property as well as e-mail and password text fields. We would generally build the views in viewDidLoad or define each as a <a href="http://twitter.com/IBOutlet">@IBOutlet</a> in an actual view controller.</p><p>After that, we made a class method that creates a LoginViewController and sets the authService. It takes any type that conforms to the AuthenticatorAdapterProtocol.</p><p>Finally, we called created a log in function and used the log in method of the authService, so that we can log in using the e-mail address and password entered in the text fields.</p><h4>Moment of truth, let&#39;s test it out</h4><p>Write down the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91d2db53c54e71c096ab54ab273a53fe/href">https://medium.com/media/91d2db53c54e71c096ab54ab273a53fe/href</a></iframe><p>We should see the output below on the console:</p><pre>Login successful.<br>Email: kimyon@catmail.com<br>Token: 64236324.375928.23934324</pre><p>We could develop adapters for new APIs, such as Facebook login, and have the LoginViewController use them in the same way without having to change any code.</p><h3>Be careful when…</h3><p>You may use the adapter pattern to conform to a new protocol without having to change the underlying type. This protects you against future changes to the underlying type, but it also makes your implementation more difficult to comprehend and maintain. So document your adapters. Add descriptions and comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*CiA4Kl_sF4P6kyun" /></figure><p>If you’re going to use the adapter pattern, make sure you’re aware of the likelihood of change. If there isn’t, evaluate whether using the objects directly makes more sense.</p><p>Congratulations. You&#39;ve made it to the end.</p><p>This is a great pattern to learn and implement, since it&#39;s used on almost every app out on the market. This will be a great asset to your coding arsenal.</p><p>I hope that the above explanation makes sense and will be helpful to you on your iOS development journey.</p><p>Thanks for reading. Have a great one.</p><p>References:</p><ul><li><a href="https://www.raywenderlich.com/">raywenderlich.com</a></li><li><a href="https://refactoring.guru/">refactoring.guru</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5fb0ac73743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder Pattern in Swift for Beginners]]></title>
            <link>https://medium.com/swift2go/builder-pattern-in-swift-for-beginners-79415d30872e?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/79415d30872e</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[optionset]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Sat, 19 Dec 2020 10:58:07 GMT</pubDate>
            <atom:updated>2020-12-19T15:21:40.087Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Have you ever not been able to create an object, just because you haven’t got all the parameters in hand?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*SKd3S1r_RwkTqb7_dd7RvQ.gif" /><figcaption>Gif by <a href="https://jambonbon.tumblr.com/post/52200871651/burger-flip-created-for-this-months-loopdeloop">Jambonbon</a> on <a href="https://jambonbon.tumblr.com/">Tumblr</a></figcaption></figure><p>I hope you are not hungry, because we will use hamburgers as metaphor.</p><h3><strong>Table of Contents</strong></h3><p>1. Introduction<br>2. Director, Builder, Product<br>3. When should you use it?<br>4. Implementation<br>5. Be careful when<br>6. Conclusion</p><h3><strong>1. Introduction</strong></h3><p>In swift, we have initializers. If we want to have an instance of an object, we create it using init function inside the struct or class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*7KQ32vqQKIJSPjJKeKP05A.png" /></figure><p>In case of a hamburger, the initializer would look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*t44UCiipQEejsvOkARal6Q.png" /></figure><p>To create a Hamburger object, we have to fill each parameter requested by init.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNI7yPnqZ2UoTs_87fH9EA.png" /></figure><p>What if we needed an hamburger without any sauce or any topping? Or what if I want to add toppings first then sauces? Or what if there is a case that we don’t have all the parameters at hand?</p><p>We can create alternative init functions. But it’s a duplication of code. Even if we tried, half way there, we would think “There has to be a better way”.</p><p>That is when the topic of this article, comes in handy. Builder design pattern is a <em>creational design pattern</em> that <strong>builds an object step by step </strong>without having to change the recipe, like a hamburger.</p><p>You can even turn builder function to <strong>composable</strong> to have more elegant looking dot syntax. A most of 3rd party swift libraries, makes developer’s life easier by taking advantage of builder pattern, such as RxSwift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*J-UlpOCKgfiFWQ1QPJj0mQ.png" /><figcaption>Builder with composables. Used as dot syntax. Looks way more professional.</figcaption></figure><p>Implementations may vary from developer to developer. You can make this more advanced or primitive, whichever is suited for your needs.</p><p>Below implementation is a basic version and using metaphor. Nevertheless, it will give you a good grasp on the concept.</p><p>We will use Playground. So create a new .playground, save it and proceed.</p><h3>2. Director, Builder, Product</h3><p>Builder design pattern has three main actors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*asD8d7AMFneTuQ1bOh3Q1A.png" /></figure><p><strong>Director </strong>accepts inputs and coordinates with the builder. This is usually a view controller or a helper class that’s used by a view controller. It takes a builder as a parameter, and uses the returned Product however it wants.</p><p><strong>Tip:</strong> Since the Builder is a dependency of the Director, what we will do below is making it “loosely coupled”. Which is a good practice for future. However, it doesn’t have to take a builder as a parameter. The builder can also be embedded inside the director. It is called “tightly coupled” and usually is a bad practice.</p><p><strong>Builder</strong> is the one accepts step-by-step inputs and handles the creation of the product. This is often a class, so it can be reused by reference. Here is where we can implement our “setters”.</p><p><strong>Tip: </strong>A way to make the builder more advanced, is to creating Builder as a protocol, and having different concrete Builder classes to implement necessary Builder protocol functions, such as “<em>build()</em>”. And implement each concrete class however you want.</p><p><strong>Product</strong> is the complex object to be created. This can be either a struct or a class, depending on desired reference semantics. It’s usually a model, but it can be any type depending on your use case.</p><p><strong>Tip: </strong>I couldn’t come up with a tip about Product, but here’s a one for hamburger! <strong>Minimize</strong> the amount of spice you mix to the meat. <strong>Rest</strong> the meat at least half an hour. Flat out the minced meat <strong>wider</strong><em> </em>than the bread’s width.</p><h3>3. When should you use it?</h3><p>Use the builder pattern when you want to create a complex object using a series of steps.</p><p>This pattern works especially well when a product requires <em>multiple inputs</em>. The builder abstracts how these inputs are used to create the product, and it accepts them in whatever order the director wants to provide them. Below are some real life examples:</p><ul><li>User fills a form (sign up, survey, etc.)</li><li>User creates custom object (question, flash card, game level, collage, etc.)</li><li>User creates their order (pizza toppings)</li></ul><h3>4. Implementation</h3><h4>Create Product</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/316962416a3729249f5455c8ec4cb8d6/href">https://medium.com/media/316962416a3729249f5455c8ec4cb8d6/href</a></iframe><p>We first define Hamburger, which has properties for meat, sauce and toppings. Why are they “<em>let</em>”, because once you make a hamburger, you can’t change it.</p><ol><li>We declare Meat as an enum. Let’s say each hamburger must have exactly <em>one </em>meat selection. (I’m not sure whether tofu can be classified as a meat selection. Sorry if that’s wrong.)</li><li>We define Sauces and Toppings as an OptionSet. This will allow you to combine multiple sauces together. We’re gonna need more than pickles for a good burger!</li><li>CustomStringConvertible extensions will help us print a readable string.</li></ol><p><strong>Tip: </strong>OptionSet is a protocol that presents a mathematical set interface to a bit set. It helps us implement single, multiple or no selection option way of structures. Don’t worry about it now. Yet definitely check it out later. For more info: <a href="https://developer.apple.com/documentation/swift/optionset">https://developer.apple.com/documentation/swift/optionset</a></p><h4>Create Builder</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2d9548c1f8bcb3ae909c97e92923ca/href">https://medium.com/media/cd2d9548c1f8bcb3ae909c97e92923ca/href</a></iframe><p>We declare properties for meat, sauces and toppings, which exactly match the inputs for Hamburger. Unlike a Hamburger, you declare these using var to be able to change them. You also specify private(set) for each to ensure <strong>only</strong> HamburgerBuilder can set them directly.</p><p>Since you declared each property using private(set), you need to provide public methods to change them. You do so via addSauces(_:), removeSauces(_:), addToppings(_:), removeToppings(_:) and setMeat(_:).</p><p>Lastly, you define build() to create the Hamburger from the selections. private(set) forces consumers to use the public setter methods. This allows the Builder to perform <em>validation </em>before setting the properties.<br>For example, you might want to ensure a meat is available prior to setting it.</p><h4>Implement Director</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac6168f6e8de4bd0dc92159a28886f88/href">https://medium.com/media/ac6168f6e8de4bd0dc92159a28886f88/href</a></iframe><p>A BurgerShop knows how to create two burgers: createCheeseBurger and createVegetarianBurger. Director can implement its own functions.</p><h4>Moment of Truth</h4><p>We’re finally ready to see this code in action. Add the following at the end of the playground:</p><p><strong>With Director, using predefined Builder functions:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc6d4e2bfcb9a063c81c7662db74eca6/href">https://medium.com/media/bc6d4e2bfcb9a063c81c7662db74eca6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASB25xfdbj3XWRgDXyI5ag.png" /></figure><p><strong>Remember: </strong>In real life, the Director has usually a tableView or textView or anything. And it builds as inputs come from the user.</p><p>What if we don’t have a predefined function and will build our burger as inputs come?</p><p><strong>Without predifened functions:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06f8ad592712c6839b622109364d1411/href">https://medium.com/media/06f8ad592712c6839b622109364d1411/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_onjn71TVIs2VOM0V5YZg.png" /></figure><h3><strong>5. Be careful when</strong></h3><p>The builder pattern works best for creating complex products that require multiple inputs using a series of steps. If your product doesn’t have several inputs or can’t be created step by step, the builder pattern may be more trouble than it’s worth.</p><p>Instead, consider providing convenience initializers to create the product.</p><h3><strong>6. Conclusion</strong></h3><ul><li>The builder pattern is great for creating complex objects in a step-by-step fashion. It involves three objects: the director, product and builder.</li><li>The director accepts inputs and coordinates with the builder; the product is the complex object that’s created; and the builder takes step-by-step inputs and creates the product.</li><li>This pattern can be more advanced or more primitive regarding with the requirement or architectural decisions. Directors can use multiple builders as parameter. Builders can create composable objects for passing it to the next operation.</li></ul><p>I hope this article will be useful to you. Have a great one.</p><p><strong>References</strong><br>raywenderlich.com<br>refactoring.guru/design-patterns/builder<br>developer.apple.com/documentation/swift</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79415d30872e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift2go/builder-pattern-in-swift-for-beginners-79415d30872e">Builder Pattern in Swift for Beginners</a> was originally published in <a href="https://medium.com/swift2go">Swift2Go</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS 14 — Modern Cell Configuration for Beginners (Programmatically)]]></title>
            <link>https://medium.com/swlh/ios-14-modern-cell-configuration-for-beginners-programmatically-2a1be3f12a90?source=rss-ff5b1211e6b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a1be3f12a90</guid>
            <category><![CDATA[uitableviewcell]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <dc:creator><![CDATA[activesludge]]></dc:creator>
            <pubDate>Sun, 08 Nov 2020 11:42:23 GMT</pubDate>
            <atom:updated>2020-11-12T03:06:58.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS 14 — Modern Cell Configuration for Beginners (Programmatically)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nn_Djk-wMKNwd-5MSTTNFw.png" /></figure><blockquote><strong>Configurations</strong> let you focus on what you want to display without worrying about how to update all of your views.</blockquote><h3>0. Table of Content</h3><ol><li>Introduction</li><li>Create Table View</li><li>How were we doing it before?<br>3.a. Legacy Implementation<br>3.b. Okay, but why has this needed an update?</li><li>How can we use Apple’s new API?<br>4.a. Modern Implementation<br>4.b. Okay, but what is better now?<br>4.c. How is this possible?<br>4.d. Keep in mind</li><li>Conclusion</li><li>References</li></ol><h3>1. Introduction</h3><p>In WWDC 2020, Apple has announced a brand new API to set up and configure cells in our table and collection views (and also stack views), which they call “Modern Cell Configuration”</p><p>In iOS 14, this new feature can be broadly separated into three categories:</p><p>· How we populate data,</p><p>· How we define the layout,</p><p>· How we display content.</p><p>I will implement the whole code without using the Main.storyboard, in other word <em>programmatically</em>.</p><p>We will focus on configuring the content and styling of the cells. I will use a default UITableView and a default UITableViewCell for simplicity. Once we get this done, I’m sure that you can implement the same idea by yourself with a little experimentation.</p><p>Even though we will implement pretty basic things, if you are new to UITableView or UICollectionView, I would highly recommend you to look at some examples before diving into this topic. Otherwise, you might feel confused.</p><h3>2. Create Table View</h3><p>You need to finish implementing TableView to see the result, so bear with me until the end.</p><p>Create a new project and save it wherever you want.</p><p>Below is how I implement the tableView, you can use your own style. It will have 10 rows and fill the whole view bound.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/448bbf70608e1ac3b2806aeea3212fca/href">https://medium.com/media/448bbf70608e1ac3b2806aeea3212fca/href</a></iframe><p>Then go ahead and create a new file inside the navigation controller name “CustomTableViewCell”. We won’t need awakeFromNib() and setSelected functions, so you can delete them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c7a294df6f9a98f8e99b23216568d20/href">https://medium.com/media/8c7a294df6f9a98f8e99b23216568d20/href</a></iframe><h3>3. How were we doing it before?</h3><h4><strong>3.a. Legacy Implementation</strong></h4><p>Usually, programmers configure the reusable cell inside cellForRowAt function between cell variable and return statement like below:</p><pre>cell.textLabel?.text = &quot;Hello World&quot;<br>cell.imageView?.image = UIImage(systemName: &quot;bell&quot;)</pre><h4>3.b. Okay, but why has this needed an update?</h4><p>Normally we have to check indexPath.row and handle some states and it can become very heavy to solve with a lot of redundant code in the view controller.</p><p>If (isSomething) do this styling, else if (isAnotherThing) do another styling, else do default styling. This can tire eyes and makes it hard to debug.</p><p>We were using “a reusable cell” but configuring it over and over again with each call. Unironically, we were <strong>not reusing</strong> the most repeated parts.</p><p>Plus, the processor has to do this check every time the cell is reused, which is a waste of energy and performance. This might not be a problem with 10 rows, but imagine 10,000 rows with infinite scroll… Things can get slow.</p><h3>4. How can we use Apple’s new API?</h3><h4><strong>4.a. Modern Implementation</strong></h4><p>What we are doing is:</p><ol><li>Declare a variable for default content configuration for the cell</li><li>Modify that the default configuration using the API’s provided dot syntax.</li><li>Assign default configuration to the cell’s content configuration.</li></ol><p>Inside CutomTableViewCell.swift file add below updateConfiguration method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec19e1e96bae7088f18a371eb086cbf/href">https://medium.com/media/4ec19e1e96bae7088f18a371eb086cbf/href</a></iframe><p>Let’s break down each statement above.</p><ul><li><strong>override func updateConfiguration(using state: UICellConfigurationState)</strong></li></ul><p>This function is called by the API for cells that are created for the tableView. It updates the cell’s configuration using the current state. It’s managed automatically behind the scene.</p><ul><li><strong>super.updateConfiguration(using: state)</strong></li></ul><p>Since we are overriding a function, we should inherit all previously defined properties and functions so we don’t miss out on anything unknown or invisible to us.</p><ul><li><strong>state</strong></li></ul><p>This indicates the possible states of the cell. It has a collection of traits. It can be Highlighted, Selected, any other custom states, etc. It has predefined variables and methods to be useful.</p><p>As in the example above, we change the style based on the state if it’s highlighted or selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rBCa9O1nSEZjW7BaWdPHgA.gif" /></figure><ul><li><strong>defaultContentConfiguration()</strong></li></ul><p>The default content configuration has preconfigured default styling but doesn’t contain any content. After you get the default configuration, you assign your content to it, customize any other properties, and assign it to the cell as the current contentConfiguration.</p><ul><li><strong>backgroundConfiguration</strong></li></ul><p>The current background configuration of the cell.</p><p>UITableViewCell automatically sets up a default background configuration to provide its default appearance.</p><p>Using a background configuration, you can obtain system default background styling for a variety of different cell states. Create a background configuration with one of the default system styles, customize the configuration to match your cell’s style as necessary, and assign the configuration to this property.</p><ul><li><strong>.updated(for: state)</strong></li></ul><p>Generates a configuration for the specified state by applying the configuration’s default values for that state to any properties that you haven’t customized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*1trElMn-qpQCy0wQ6hOPYQ.gif" /></figure><ul><li><strong>contentConfiguration = contentConfig </strong>and<strong><br>backgroundConfiguration = backgroundConfig</strong></li></ul><p>This is the final step. <strong>contentConfig</strong> and <strong>backgroundConfig </strong>variables<strong> </strong>now contains our configurations. We need to assign them, to the cell configurations. Allowing the cell will use these two variables as content and background configurations.</p><p>As soon as we do this, the cell is updated to display the image, text, and background that we specified.</p><p>Please run and see how it goes.</p><h4><strong>4.b. Okay, but what is better now?</strong></h4><p>Now, before this line of code, setting the image and text only changed our local copy of the configuration stored in this “content” variable.</p><p>Because we’re using a content configuration, we never directly touch a UIImageView or UILabel. All of the properties are set on the configuration itself.</p><p>Well, for one, the code that we see here to configure a table view cell is almost the same code we would use to configure any cell. In fact, the same code works for any view that supports content configurations, even ones that aren’t cells, such as table view headers and footers.</p><p>Configurations are lightweight. We can use them as a source of default values for things like fonts, colors, and margins that you copy over to our custom views, even if we never apply the configuration directly itself.</p><p>For more advanced use cases, you can create a completely custom content configuration type with a paired content view class that renders it, and then use your custom configuration with any cell the same way that you would use a list content configuration.</p><p>And because the list content view is just a regular UIView, you can actually use it by itself anywhere, even outside of a collection or table view, such as in a plain UIStackView.</p><h4><strong>4.c. How is this possible?</strong></h4><p>This works because configurations are composable.</p><p>Instead of all of the functionality being baked into the cell class itself, like it was with UITableViewCell, these standard cell layouts and appearances are now available as independent pieces that can plug right into any cell or view that supports them.</p><h4><strong>4.d. Keep in mind</strong></h4><p>If you have existing code that you’re going to update and migrate over, configurations are mutually exclusive with some existing properties.</p><p>It seems that setting a background configuration always resets the background color and background view properties to nil. So make sure that you don’t mix a background configuration with other code still setting these other background properties on the same cell.</p><p>Content configurations replace the built-in subviews of cells, headers, and footers, like the imageView, textLabel, and detailTextLabel.</p><p>These legacy content properties seem to be eliminated in a future release, so Apple encourages us to adopt content configurations to take advantage of their more powerful features and enhanced customizability.</p><h3><strong>5. Conclusion</strong></h3><ul><li>Apple wants to put a standard API for one of the most used parts of their UIKit library, which we were doing manually until now. I think most of the developers were expecting something like this.</li><li>New API will figure out what’s changed and efficiently update the views as needed.</li><li>We may now assign default cell properties, and let the API handle the configurations. UIKit seems to handle the heavy lifting. Certainly, this will handle memory management better than the legacy way.</li><li>Configurations act as a single source.</li><li>It seems very easy to adopt.</li><li>This new API has great potential.</li></ul><h3><strong>6. References</strong></h3><ul><li>Apple Developer Documentation</li><li>WWDC 2020</li></ul><p>I hope that this article can be useful to you. Have a great one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a1be3f12a90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/ios-14-modern-cell-configuration-for-beginners-programmatically-2a1be3f12a90">iOS 14 — Modern Cell Configuration for Beginners (Programmatically)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>