<?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 khaled kamal on Medium]]></title>
        <description><![CDATA[Stories by khaled kamal on Medium]]></description>
        <link>https://medium.com/@khaledkamal?source=rss-5a916709b0c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nwf0s5oQp7BsCkJL3HBwzA.jpeg</url>
            <title>Stories by khaled kamal on Medium</title>
            <link>https://medium.com/@khaledkamal?source=rss-5a916709b0c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:31:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khaledkamal/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[Kotlin Extension Functions vs Swift Extensions: Static Dispatch, Dynamic Dispatch & Polymorphism]]></title>
            <link>https://medium.com/@khaledkamal/kotlin-extension-functions-vs-swift-extensions-static-dispatch-dynamic-dispatch-polymorphism-98fed85af48d?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/98fed85af48d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 09:12:44 GMT</pubDate>
            <atom:updated>2026-11-26T09:12:44.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsgCC8YeGv_L3d_cszn-dA.jpeg" /></figure><p><em>Why extensions don’t behave like overrides, how protocol extensions change the picture, and what this means for API design.</em></p><p>Have you ever added a method to an existing type using an extension, then expected it to behave like an overridden method?</p><p>This is one of those concepts that looks simple at first but can lead to surprising behavior in real applications.</p><p>Both Kotlin and Swift allow us to extend existing types without modifying their original implementations.</p><p>For example:</p><ul><li>Kotlin gives us extension functions.</li><li>Swift gives us extensions.</li></ul><p>They look similar, and they serve similar purposes. But there’s an important rule to understand:</p><p><strong>Extension methods are generally resolved statically, not dynamically.</strong></p><p>Let’s explore what this means, why it matters, and where Swift introduces an interesting exception through protocol requirements.</p><h3>1. First, understand Static vs Dynamic Dispatch</h3><p>Before comparing Kotlin and Swift, let’s understand two important concepts.</p><h3>Static Dispatch</h3><p>Static dispatch means the compiler determines which implementation to call at compile time.</p><p>The decision is based on the expression’s statically known type.</p><p>In other words, the compiler doesn’t need to inspect the actual object’s runtime type to select the implementation.</p><h3>Dynamic Dispatch</h3><p>Dynamic dispatch means the implementation is selected at runtime based on the actual object’s type.</p><p>This is what makes method overriding and polymorphism possible.</p><p>For example, imagine we have:</p><ul><li>An Animal type.</li><li>A Cat type that inherits from Animal.</li><li>A speak() method is implemented differently by each type.</li></ul><p>When we call speak() through an Animal reference, dynamic dispatch allows the Cat implementation to execute.</p><p>This is the foundation of polymorphism.</p><p>Now let’s see how extensions behave.</p><h3>2. Kotlin: Extension Functions Are Statically Resolved</h3><p>Kotlin allows us to add functions to existing types without modifying their original classes.</p><p>Consider this example:</p><pre>open class Animal<br>class Cat : Animal()</pre><pre>fun Animal.speak() = &quot;...&quot;<br>fun Cat.speak() = &quot;meow&quot;</pre><pre>fun greet(animal: Animal) {<br>    println(animal.speak())<br>}</pre><pre>greet(Cat())</pre><p>What do you expect the output to be?</p><p>You might expect:</p><pre>meow</pre><p>Because the actual object is a Cat.</p><p>But the actual output is:</p><pre>...</pre><p>Why?</p><p>Look at the function:</p><pre>fun greet(animal: Animal) {<br>    println(animal.speak())<br>}</pre><p>The parameter is declared as Animal.</p><p>Therefore, when the compiler encounters:</p><pre>animal.speak()</pre><p>It resolves the extension using the declared type, which is Animal.</p><p>It doesn’t matter that the actual object passed at runtime is a Cat.</p><p><strong>Kotlin extension functions are statically dispatched based on the receiver’s declared type.</strong></p><h3>What if we use a real member function?</h3><p>Let’s change the example:</p><pre>open class Animal {<br>    open fun speak() = &quot;...&quot;<br>}</pre><pre>class Cat : Animal() {<br>    override fun speak() = &quot;meow&quot;<br>}</pre><pre>fun greet(animal: Animal) {<br>    println(animal.speak())<br>}</pre><pre>greet(Cat())</pre><p>Output:</p><pre>meow</pre><p>Now we get the expected result!</p><p>Why?</p><p>Because speak() is a real member function, and Kotlin supports dynamic dispatch through overriding.</p><p>The runtime type determines which implementation executes.</p><h3>Kotlin takeaway</h3><p>Extensions provide additional functionality, but they don’t participate in polymorphic overriding.</p><p>You can define another extension with the same name for a more specific type, but that doesn’t mean you’re overriding the original extension.</p><h3>3. Swift: Class Extensions Follow the Same Principle</h3><p>Swift also allows us to extend existing types.</p><p>Let’s reproduce the same example:</p><pre>class Animal {}<br>class Cat: Animal {}</pre><pre>extension Animal {<br>    func speak() -&gt; String {<br>        &quot;...&quot;<br>    }<br>}</pre><pre>extension Cat {<br>    func speak() -&gt; String {<br>        &quot;meow&quot;<br>    }<br>}</pre><pre>func greet(_ animal: Animal) {<br>    print(animal.speak())<br>}</pre><pre>greet(Cat())</pre><p>Output:</p><pre>...</pre><p>Surprised?</p><p>The actual object is a Cat, but the parameter is declared as Animal.</p><p>Swift resolves the extension method based on the static type of the expression.</p><p>This is essentially the same behavior we observed in Kotlin.</p><h3>What if we use a real member function?</h3><pre>class Animal {<br>    func speak() -&gt; String {<br>        &quot;...&quot;<br>    }<br>}</pre><pre>class Cat: Animal {<br>    override func speak() -&gt; String {<br>        &quot;meow&quot;<br>    }<br>}</pre><pre>func greet(_ animal: Animal) {<br>    print(animal.speak())<br>}</pre><pre>greet(Cat())</pre><p>Output:</p><pre>meow</pre><p>Just like Kotlin, Swift supports dynamic dispatch for overridden class methods.</p><p><strong>Important:</strong> Swift extensions cannot override existing methods or add stored properties to existing types.</p><h3>4. Swift’s Interesting Part: Protocol Extensions</h3><p>Here’s where Swift introduces an important distinction.</p><p>Swift allows us to add default implementations to protocol methods through protocol extensions.</p><p>But there’s a difference between:</p><ol><li>A method declared as a protocol requirement.</li><li>A method that exists only inside a protocol extension.</li></ol><p>Let’s examine both cases.</p><h3>Case A: Method declared in the protocol</h3><pre>protocol Animal {<br>    func speak() -&gt; String<br>}</pre><pre>extension Animal {<br>    func speak() -&gt; String {<br>        &quot;...&quot;<br>    }<br>}</pre><pre>struct Cat: Animal {<br>    func speak() -&gt; String {<br>        &quot;meow&quot;<br>    }<br>}</pre><pre>func greet(_ animal: Animal) {<br>    print(animal.speak())<br>}</pre><pre>greet(Cat())</pre><p>Output:</p><pre>meow</pre><p>Why?</p><p>Because speak() is declared as a protocol requirement.</p><p>When Cat conforms to Animal, it provides its own implementation.</p><p>When we call speak() through the protocol type, Swift uses dynamic dispatch through the protocol witness table to select the conforming type&#39;s implementation.</p><p>Even though we’re calling the method through an Animal reference, the actual implementation belongs to Cat.</p><h3>Case B: Method exists only in the protocol extension</h3><p>Now let’s remove speak() from the protocol itself:</p><pre>protocol Animal {}</pre><pre>extension Animal {<br>    func speak() -&gt; String {<br>        &quot;...&quot;<br>    }<br>}</pre><pre>struct Cat: Animal {<br>    func speak() -&gt; String {<br>        &quot;meow&quot;<br>    }<br>}</pre><pre>func greet(_ animal: Animal) {<br>    print(animal.speak())<br>}</pre><pre>greet(Cat())</pre><p>Output:</p><pre>...</pre><p>Why?</p><p>Because speak() is not a protocol requirement.</p><p>It’s simply a method provided by the protocol extension.</p><p>Swift resolves this call statically using the extension implementation.</p><p>The fact that Cat has another method with the same name doesn&#39;t change which implementation is selected through the Animal protocol type.</p><p>This is one of the most important distinctions when working with Swift protocols.</p><h3>An additional detail</h3><p>If we call the method directly on the concrete type:</p><pre>let cat = Cat()<br>print(cat.speak())</pre><p>The output is:</p><pre>meow</pre><p>Why?</p><p>Because the compiler knows the concrete type is Cat, so it resolves the call to Cat.speak().</p><p>But when we call it through an Animal reference, the extension implementation is selected.</p><p>The static type of the expression matters!</p><h3>5. Kotlin vs Swift: The Complete Comparison</h3><p>Let’s summarize the behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEuGIF5yrsGW2r1FoGq58A.png" /></figure><p>The most important thing to remember is that extension methods don’t automatically become polymorphic just because the language supports inheritance or protocols.</p><p>A protocol extension can provide a default implementation, but if you need conforming types to dynamically customize that behavior, the method must be declared as a protocol requirement.</p><h3>6. Practical Implications for API Design</h3><p>Understanding dispatch isn’t just about predicting what a code snippet prints.</p><p>It affects how we design reusable APIs.</p><p>Imagine we’re building a payment system.</p><p>We have different payment providers:</p><ul><li>Credit Card</li><li>PayPal</li><li>Apple Pay</li></ul><p>We want each payment provider to implement its own processing behavior.</p><p>A good approach is to use a <strong>protocol or interface requirement</strong>.</p><h3>Swift example</h3><pre>protocol Payment {<br>    func process()<br>}</pre><pre>extension Payment {<br>    func process() {<br>        print(&quot;Default payment processing&quot;)<br>    }<br>}</pre><pre>struct CreditCard: Payment {<br>    func process() {<br>        print(&quot;Processing credit card&quot;)<br>    }<br>}</pre><pre>struct PayPal: Payment {<br>    func process() {<br>        print(&quot;Processing PayPal&quot;)<br>    }<br>}</pre><pre>func checkout(_ payment: Payment) {<br>    payment.process()<br>}</pre><p>Now each payment type provides its own implementation, and dynamic dispatch ensures the correct implementation is called.</p><h3>When should we use extensions?</h3><p>Extensions are excellent for:</p><ul><li>Adding convenience methods.</li><li>Grouping related functionality.</li><li>Providing default implementations.</li><li>Adding functionality to types we don’t own.</li><li>Improving API readability.</li></ul><p>For example:</p><pre>extension String {<br>    var isValidEmail: Bool {<br>        contains(&quot;@&quot;)<br>    }<br>}</pre><p>But if the behavior must vary depending on the actual object type, use a real member override or a protocol/interface requirement.</p><p>Don’t rely on extensions to provide polymorphism.</p><h3>7. Final Takeaways</h3><p>Here are the concepts worth remembering:</p><p><strong>Kotlin:</strong></p><ul><li>Extension functions are resolved statically.</li><li>Their implementation depends on the receiver’s declared type.</li><li>They cannot be overridden.</li><li>Member functions support dynamic dispatch through overriding.</li></ul><p><strong>Swift:</strong></p><ul><li>Class extension methods are statically resolved.</li><li>Class member overrides support dynamic dispatch.</li><li>Protocol requirements support dynamic dispatch.</li><li>Protocol extension-only methods are statically resolved when called through a protocol type.</li></ul><h3>One question to remember</h3><p>If you have a method that should behave differently depending on the actual object’s type, should you implement it as an extension or as a member/protocol requirement?</p><p>The answer is simple:</p><p><strong>Use extensions to add functionality. Use polymorphism to provide varying behavior.</strong></p><p>Understanding this distinction helps us write more predictable APIs and avoid subtle bugs in both Kotlin and Swift.</p><p><em>What’s your experience with extension functions in Kotlin or Swift? Have you ever encountered this behavior unexpectedly? I’d love to hear your thoughts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98fed85af48d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Overengineering Your Mobile Architecture]]></title>
            <link>https://medium.com/@khaledkamal/stop-overengineering-your-mobile-architecture-94f7a30b5ed2?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/94f7a30b5ed2</guid>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 17:14:49 GMT</pubDate>
            <atom:updated>2026-10-30T17:14:49.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_Tkny-PS7Zxq73nFoylEQ.jpeg" /></figure><p><em>Why I prefer starting simple, organizing by feature, and introducing abstractions only when they solve real problems.</em></p><p>Have you ever worked on a simple mobile feature and ended up creating:</p><ul><li>A View</li><li>A ViewModel</li><li>An Interactor</li><li>A UseCase</li><li>A Repository</li><li>A Repository Implementation</li><li>A DataSource</li><li>A Network Service</li></ul><p>All just to fetch a list from an API?</p><p>It raises an interesting question:</p><p><strong>Are we building better architecture, or just adding more layers?</strong></p><p>My philosophy is simple:</p><blockquote><em>Architecture should reduce complexity, not create folders.</em></blockquote><p>As mobile engineers, we shouldn’t choose an architecture just because it’s popular or because a big company uses it.</p><p>We should choose it based on the problems we’re trying to solve.</p><p>In this article, I’ll share how I approach architecture in modern iOS applications, why I prefer starting simple, and when I believe additional architectural layers are actually worth introducing.</p><h3>1. Start with a Simple Architecture</h3><p>For most mobile features, I’d start with something straightforward:</p><pre>Feature<br>                |<br>                ▼<br>               View<br>                |<br>                ▼<br>            ViewModel<br>                |<br>                ▼<br>            Repository<br>                |<br>          +-----+-----+<br>          |           |<br>        Remote       Local<br>         API           DB</pre><p>Each component has a clear responsibility:</p><ul><li><strong>View:</strong> Displays the UI and forwards user interactions.</li><li><strong>ViewModel:</strong> Manages screen state and presentation logic.</li><li><strong>Repository:</strong> Provides data without exposing where it comes from.</li><li><strong>Data Sources:</strong> Fetch data from remote APIs or local storage.</li></ul><p>That’s enough for many features.</p><p>I don’t introduce separate Domain, UseCase, or additional abstraction layers unless the complexity actually justifies them.</p><p>Why?</p><p>Because every additional abstraction has a cost. It adds code to maintain, understand, test, and navigate.</p><p>The goal isn’t to have fewer files at any cost. It’s to avoid abstractions that don’t provide meaningful value.</p><h3>2. When Architecture Becomes Overengineering</h3><p>Sometimes, architecture evolves into something like this:</p><pre>View<br>  ↓<br>ViewModel<br>  ↓<br>Interactor<br>  ↓<br>UseCase<br>  ↓<br>Repository<br>  ↓<br>RepositoryImpl<br>  ↓<br>DataSource<br>  ↓<br>RemoteDataSource<br>  ↓<br>APIClient<br>  ↓<br>NetworkManager<br>  ↓<br>Service</pre><p>There is nothing inherently wrong with these components. Each can be useful when it protects a meaningful boundary.</p><p>But do we really need all of them for a simple GET request?</p><p>Sometimes we’re introducing abstractions without solving an actual problem.</p><p>I call this <strong>architecture theater</strong>: adding architectural complexity without getting meaningful architectural benefits.</p><p>The important question isn’t:</p><p>“How many layers should we have?”</p><p>It’s:</p><p><strong>“Which boundaries protect us from change?”</strong></p><h3>3. Feature-First vs. Layer-First Architecture</h3><p>Another decision I care about is how we organize our code.</p><p>A traditional layer-first structure might look like this:</p><pre>Presentation/<br>Domain/<br>Data/<br>Network/<br>Models/<br>Repositories/<br>UseCases/<br>Services/</pre><p>This works, but as an application grows, working on one feature might require navigating several different folders.</p><p>I generally prefer a feature-first structure:</p><pre>Features/<br>    Schedule/<br>        ScheduleView<br>        ScheduleViewModel<br>        ScheduleRepository<br>        ScheduleModels</pre><pre>    CreateShift/<br>        CreateShiftView<br>        CreateShiftViewModel<br>        CreateShiftRepository</pre><pre>    Profile/<br>        ProfileView<br>        ProfileViewModel</pre><pre>Core/<br>    Networking/<br>    Persistence/<br>    Authentication/<br>    Analytics/</pre><pre>Shared/<br>    UI/<br>    Extensions/<br>    Utilities/</pre><p>Why?</p><p>Imagine you’re working on the Create Shift feature.</p><p>You can find most of its related code in one place instead of navigating between Presentation, Domain, Data, and Repository folders.</p><p>But there’s another benefit that becomes important as the application grows.</p><p><strong>Architecture is also about organizing teams.</strong></p><p>Good feature boundaries can help teams work independently, reduce unnecessary coordination, and make ownership clearer.</p><p>Of course, creating a folder for every feature doesn’t automatically create modularity.</p><p>Real modularity requires clear interfaces, controlled dependencies, and well-defined ownership.</p><p>My preference is:</p><blockquote><em>Organize by feature first, then introduce layers inside a feature when necessary.</em></blockquote><h3>4. Does Every Feature Need Clean Architecture?</h3><p>Absolutely not.</p><p>I like Clean Architecture, but I prefer applying its principles rather than blindly following its folder structure.</p><p>Let’s compare two situations.</p><p><strong>Case A: A simple feature</strong></p><p>Imagine a screen that fetches a list of shifts.</p><pre>CreateShift/<br>    CreateShiftView<br>    CreateShiftViewModel<br>    CreateShiftRepository<br>    CreateShiftModel</pre><p>This might be all you need.</p><p>Introducing separate Domain, Data, UseCase, and Repository Implementation layers could add unnecessary complexity.</p><p><strong>Case B: A complex feature</strong></p><p>Now imagine a feature that handles:</p><ul><li>Employee selection</li><li>Permission validation</li><li>Business rules</li><li>Shift calculations</li><li>Offline support</li><li>Multiple data sources</li></ul><p>Here, separating responsibilities becomes more valuable.</p><pre>CreateShift/<br>│<br>├── Presentation/<br>│   ├── CreateShiftView<br>│   └── CreateShiftViewModel<br>│<br>├── Domain/<br>│   ├── CreateShiftUseCase<br>│   ├── Shift<br>│   └── ShiftRepository<br>│<br>└── Data/<br>    ├── CreateShiftRepositoryImpl<br>    ├── ShiftAPI<br>    └── ShiftDTO</pre><p>The difference is the complexity of the problem, not the size of the feature folder.</p><p><strong>Architecture should grow with complexity.</strong></p><h3>5. When Do Use Cases Actually Make Sense?</h3><p>This is one of the things I think developers should understand before adopting Clean Architecture.</p><p>A UseCase isn’t something we should create just because every operation needs one.</p><p>Consider a simple operation:</p><pre>let shifts = try await repository.shifts()</pre><p>What additional value does a GetShiftsUseCase Provide here?</p><p>Maybe nothing. The repository already gives us what we need.</p><p>Now consider a more complicated operation:</p><pre>Fetch Schedule<br>      ↓<br>Check Permissions<br>      ↓<br>Fetch Employees<br>      ↓<br>Merge Shifts<br>      ↓<br>Apply Business Rules<br>      ↓<br>Calculate Overtime<br>      ↓<br>Filter Unavailable Employees<br>      ↓<br>Return Schedule</pre><p>Now we have actual business logic and orchestration.</p><p>This is where a UseCase makes sense.</p><p>It gives us a dedicated place to organize and test that logic independently.</p><p>My rule is simple:</p><blockquote><em>Don’t create a UseCase because the architecture diagram says so. Create it because the business logic needs it.</em></blockquote><h3>6. What About MVVM?</h3><p>For modern SwiftUI applications, I generally prefer a straightforward MVVM approach:</p><pre>SwiftUI View<br>     ↓<br>  ViewModel<br>     ↓<br> Repository<br>     ↓<br> Data Sources</pre><p>Apple’s SwiftUI model is fundamentally based around <strong>state and data flow</strong>, where views derive their UI from state rather than manually manipulating the UI hierarchy. (<a href="https://developer.apple.com/wwdc19/226">Apple Developer</a>)</p><p>Here’s a complete, copyable example — including the state definition and initializers I left out earlier:</p><pre>@Observable<br>final class ScheduleViewModel {</pre><pre>    enum State {<br>        case loading<br>        case loaded([Shift])<br>        case error(Error)<br>    }</pre><pre>    var state: State = .loading</pre><pre>    private let repository: ScheduleRepository</pre><pre>    init(repository: ScheduleRepository) {<br>        self.repository = repository<br>    }</pre><pre>    func load() async {<br>        do {<br>            state = .loaded(<br>                try await repository.fetchSchedule()<br>            )<br>        } catch {<br>            state = .error(error)<br>        }<br>    }<br>}</pre><p>And the View:</p><pre>struct ScheduleView: View {</pre><pre>    @State private var viewModel: ScheduleViewModel</pre><pre>    init(repository: ScheduleRepository) {<br>        _viewModel = State(initialValue: ScheduleViewModel(repository: repository))<br>    }</pre><pre>    var body: some View {<br>        // UI<br>        Group {<br>            // render viewModel.state here<br>        }<br>        .task { await viewModel.load() }<br>    }<br>}</pre><p>Notice how straightforward the interaction is.</p><p>The View observes state, the ViewModel handles presentation logic, and the Repository provides data.</p><p>I wouldn’t introduce additional layers just to make this flow look more architecturally sophisticated.</p><h3>7. What About TCA?</h3><p>TCA solves a different problem.</p><p>Imagine a screen responsible for:</p><ul><li>Employee selection</li><li>Search</li><li>Form validation</li><li>Location permissions</li><li>Network requests</li><li>Retry mechanisms</li><li>Offline states</li><li>Navigation</li><li>Analytics</li></ul><p>As the number of states and interactions grows, managing everything inside a traditional ViewModel can become difficult.</p><p>This is where an explicit state-management approach like TCA can help.</p><p>Its basic flow looks like this:</p><pre>Action<br>          ↓<br>       Reducer<br>          ↓<br>        State<br>          ↓<br>         View<br>          ↑<br>        Effect</pre><p>TCA gives us an explicit way to manage state transitions, actions, and side effects.</p><p>But I wouldn’t introduce it into every feature.</p><p>It’s a trade-off: more explicit state and effect management in exchange for additional architectural structure.</p><p><strong>Choose it when the complexity of state management justifies the investment.</strong></p><h3>8. What Do Big Companies Actually Do?</h3><p>It’s tempting to search for the architecture used by Apple, Google, Airbnb, or Netflix and try to replicate it.</p><p>But there is no universal architecture used by all successful engineering teams.</p><p>Different companies have different products, team structures, codebases, and engineering constraints.</p><p>For example, Airbnb has publicly documented its <a href="https://github.com/airbnb/mavericks">Mavericks (formerly MvRx)</a> framework, while Uber has open-sourced its <a href="https://github.com/uber/RIBs">RIBs architecture</a>, designed for large mobile applications with complex, nested business states.</p><p>The lesson isn’t that we should copy their architecture.</p><p>It’s the architecture that should solve the problems of the system we’re building.</p><p>Instead of asking:</p><p>“Which architecture does Google use?”</p><p>I’d ask:</p><pre>What problem are we solving?<br>          ↓<br>What changes frequently?<br>          ↓<br>What needs to be isolated?<br>          ↓<br>Where do we need testability?<br>          ↓<br>Where do we need independent ownership?<br>          ↓<br>Choose the appropriate boundaries.</pre><p>That’s a much better starting point.</p><h3>9. Dependency Direction Matters More Than the Pattern</h3><p>For a large existing iOS application, I’d generally move toward something like this:</p><pre>FEATURES<br>    +--------------------------------------+<br>    |                                      |<br>    |  Schedule    Chat    Feed    Absence |<br>    |     |         |       |        |     |<br>    |     ▼         ▼       ▼        ▼     |<br>    |    View      View    View     View   |<br>    |     |         |       |        |     |<br>    |   State/VM  State/VM State/VM State/VM|<br>    |     |         |       |        |     |<br>    +-----+---------+-------+--------+-----+<br>                  |<br>                  ▼<br>             REPOSITORIES<br>                  |<br>           +------+------+<br>           |             |<br>        GraphQL         Realm<br>          API          Local DB</pre><pre>                 SHARED CORE<br>    +--------------------------------------+<br>    | Authentication                       |<br>    | Networking                            |<br>    | Persistence                           |<br>    | Analytics                             |<br>    | Feature Flags                         |<br>    | Notifications                         |<br>    | Design System                         |<br>    +--------------------------------------+</pre><p>Each feature owns its presentation and feature-specific logic.</p><p>Shared infrastructure provides common capabilities without forcing every feature to know how those capabilities are implemented.</p><p>When a feature becomes genuinely complex, I’d introduce additional boundaries such as Domain, UseCases, and Data, without forcing every other feature to follow the same level of complexity.</p><p>But the diagram isn’t really the point.</p><p>What matters more than this shape, or any shape, is <strong>dependency direction</strong>.</p><p>First, let’s distinguish between two things:</p><ul><li><strong>Runtime call flow:</strong> What calls what when the application executes.</li><li><strong>Dependency direction:</strong> Which components depend on which abstractions at compile time?</li></ul><p>For example, a feature might call a repository method at runtime.</p><p>But the feature shouldn’t need to depend on the concrete GraphQL or Realm implementation.</p><p>A healthy dependency design looks like this:</p><pre>Feature<br>   |<br>   ▼<br>Repository Protocol<br>   ▲<br>   |<br>Repository Implementation<br>   |<br>   ▼<br>GraphQL / Realm / API</pre><p>The feature depends on an abstraction, while the concrete implementation satisfies that abstraction and can be injected.</p><p>Compare that with:</p><pre>View → APIClient<br>ViewModel → Realm<br>Repository → ViewModel<br>Network → Feature UI</pre><p>These dependencies make changes harder because infrastructure and presentation become unnecessarily coupled.</p><p>Imagine your application uses GraphQL today, but you decide to migrate to REST tomorrow.</p><p>In a well-bounded system, that change should mostly affect the data and infrastructure implementation.</p><p>Your View and ViewModel shouldn’t need to know or care where the data comes from.</p><p>That’s the real value of good boundaries:</p><p><strong>Isolating change.</strong></p><h3>10. My Architecture Philosophy</h3><p>If I had to summarize my preferred approach based on application complexity:</p><p><strong>Small application</strong></p><pre>View → Model / Service</pre><p><strong>Medium application</strong></p><pre>View → ViewModel → Repository → API / DB</pre><p><strong>Large application</strong></p><pre>Feature<br>    ├── Presentation<br>    ├── Domain (when needed)<br>    └── Data</pre><p><strong>Very complex feature</strong></p><pre>View<br>  ↓<br>State / Reducer<br>  ↓<br>UseCases<br>  ↓<br>Repository<br>  ↓<br>Data Sources</pre><p>Potentially using TCA or another explicit state-management approach.</p><p>These aren’t strict rules or a universal progression. They’re starting points that should change based on the actual needs of the application.</p><h3>Final Thoughts</h3><p>If there’s one thing I’d like developers to take away from this article, it’s this:</p><p><strong>Don’t start by choosing an architecture. Start by understanding the complexity.</strong></p><p>Instead of saying:</p><p>“We’re building this feature using Clean Architecture.”</p><p>Ask:</p><p>“What are the responsibilities we need to separate, and why?”</p><p>Instead of creating a UseCase for every API operation, ask:</p><p>“Is there business logic here that deserves its own boundary?”</p><p>Instead of adding another abstraction, ask:</p><p>“Does this abstraction protect us from a meaningful change?”</p><p>Good architecture isn’t about how many layers, protocols, or folders we have.</p><p>It’s about how well our system handles change without making development harder.</p><blockquote><strong><em>Build for complexity, not for folders.</em></strong></blockquote><p>And if you’re growing toward a Senior, Staff, or Architect role, I’d recommend learning these concepts independently rather than memorizing architecture patterns:</p><ol><li>Dependency Direction</li><li>Modularization</li><li>State Management</li><li>Data Flow</li><li>Business Boundaries</li><li>Persistence</li><li>Networking</li><li>Navigation</li><li>Testing</li><li>Architectural Patterns</li></ol><p>Once you understand these concepts, MVVM, Clean Architecture, TCA, and VIPER stop being competing religions.</p><p>They become tools.</p><h3>What’s your approach?</h3><p>Do you prefer starting with a simple architecture and introducing complexity when needed, or do you prefer establishing clear layers from the beginning?</p><p>I’d love to hear how other iOS and Android engineers approach this in real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94f7a30b5ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4— Custom Codable: Mastering Swift Codable]]></title>
            <link>https://medium.com/@khaledkamal/part-4-custom-codable-mastering-swift-codable-4a66478a23fe?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a66478a23fe</guid>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 12:28:07 GMT</pubDate>
            <atom:updated>2026-10-15T12:28:07.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9Sz5cEF00IndyfWM1Q_1w.jpeg" /></figure><p>We’ve moved beyond simply <em>using</em> Codable. Now it’s time to learn how to <strong>control </strong><strong>Codable</strong>.</p><p>In the previous levels, we explored how Swift maps JSON into models using synthesized decoding and encoding. But real-world APIs aren’t always consistent. They may return numbers as strings, introduce new enum values, use unexpected date formats, or represent the same field differently across endpoints.</p><p>This is where custom Codable becomes valuable.</p><p>The goal isn’t to write custom decoding for everything. It’s to understand <strong>when synthesis is no longer enough, how to handle external data safely, and how to keep your models clean as your application grows.</strong></p><h3>4.1 The Core Mental Model</h3><p>Consider a simple model:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>Swift can automatically synthesize the required decoding and encoding implementations for this type.</p><p>Conceptually, Swift provides the equivalent of:</p><pre>init(from decoder: Decoder) throws</pre><p>and:</p><pre>func encode(to encoder: Encoder) throws</pre><p>You don’t need to implement either method because the properties map naturally to the JSON representation.</p><p>But what happens when the API representation no longer matches your Swift model?</p><p>At Level 4, we take control:</p><pre>struct User: Decodable {<br>    let id: Int<br>    let name: String</pre><pre>    init(from decoder: Decoder) throws {<br>        // Define how external data maps to this model.<br>    }<br>}</pre><p>Think of the difference this way:</p><p><strong>Synthesized Codable</strong></p><p>Swift follows its standard mapping rules.</p><p><strong>Custom Codable</strong></p><p>You explicitly define how external data should be interpreted or represented.</p><p>The important skill is knowing when that additional control is necessary.</p><h3>4.2 Custom init(from:)</h3><p>Imagine the backend returns:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;name&quot;: &quot;Khaled&quot;,<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>But your application expects:</p><pre>struct User {<br>    let id: Int<br>    let name: String<br>    let age: Int<br>}</pre><p>The problem is straightforward: the backend represents id and age as JSON strings, while the Swift model expects integers.</p><p>Synthesized decoding won’t automatically convert &quot;123&quot; into 123.</p><p>We need to define that conversion ourselves.</p><h3>A custom decoding implementation</h3><pre>struct User: Decodable {<br>    let id: Int<br>    let name: String<br>    let age: Int</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case name<br>        case age<br>    }</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        let idString = try container.decode(<br>            String.self,<br>            forKey: .id<br>        )</pre><pre>        guard let id = Int(idString) else {<br>            throw DecodingError.dataCorruptedError(<br>                forKey: .id,<br>                in: container,<br>                debugDescription: &quot;Expected a valid integer string&quot;<br>            )<br>        }</pre><pre>        let name = try container.decode(<br>            String.self,<br>            forKey: .name<br>        )</pre><pre>        let ageString = try container.decode(<br>            String.self,<br>            forKey: .age<br>        )</pre><pre>        guard let age = Int(ageString) else {<br>            throw DecodingError.dataCorruptedError(<br>                forKey: .age,<br>                in: container,<br>                debugDescription: &quot;Expected a valid integer string&quot;<br>            )<br>        }</pre><pre>        self.id = id<br>        self.name = name<br>        self.age = age<br>    }<br>}</pre><p>Notice the use of guard Instead of force unwrapping.</p><p>Avoid this:</p><pre>id = Int(idString)!</pre><p>If the backend unexpectedly returns &quot;abc&quot;The conversion fails, and force unwrapping crashes the application.</p><p>A throwing decoder is the safer alternative. It allows the decoding operation to fail normally, so the caller can handle the error.</p><p><strong>Production principle:</strong> External data should never be assumed valid merely because the API usually returns the expected format.</p><h3>4.3 Understanding DecodingError</h3><p>Custom decoding becomes much easier when you understand the errors that JSONDecoder and your own decoding logic can produce.</p><p>There are four particularly important cases.</p><h3>1. keyNotFound</h3><p>The decoder requires a key, but that key is missing.</p><p>For example:</p><pre>{}</pre><p>When decoding:</p><pre>let name = try container.decode(<br>    String.self,<br>    forKey: .name<br>)</pre><p>The decoder throws DecodingError.keyNotFound.</p><p>This usually means the payload doesn’t satisfy the model’s required fields.</p><h3>2. valueNotFound</h3><p>The decoder expects a value, but the value is absent — for example, a required nonoptional value is represented by JSON null.</p><pre>{<br>    &quot;name&quot;: null<br>}</pre><p>If name is decoded as a nonoptional String, the decoder throws DecodingError.valueNotFound.</p><p>Remember the distinction: a missing key and a present key containing null are different conditions.</p><h3>3. typeMismatch</h3><p>The value exists, but its type doesn’t match what the decoder expects.</p><pre>{<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>Trying to decode age directly as an Int:</p><pre>let age = try container.decode(<br>    Int.self,<br>    forKey: .age<br>)</pre><p>produces DecodingError.typeMismatch, because &quot;25&quot; is a string rather than a JSON number.</p><h3>4. dataCorrupted</h3><p>The value cannot be interpreted according to the expected representation.</p><p>For example:</p><pre>{<br>    &quot;age&quot;: &quot;hello&quot;<br>}</pre><p>The value can be decoded as a String, but it cannot be converted into a valid integer.</p><p>This is an appropriate case for DecodingError.dataCorruptedError(...) when implementing the conversion yourself.</p><p>These categories help you diagnose whether the problem is a missing field, a null value, an incompatible type, or invalid content.</p><h3>4.4 Supporting Multiple Representations</h3><p>Real APIs sometimes represent the same logical value in different ways.</p><p>One response might contain:</p><pre>{<br>    &quot;id&quot;: 123<br>}</pre><p>Another might contain:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;<br>}</pre><p>If both representations are explicitly supported by the API contract, we can create a reusable type that accepts either.</p><h3>Introducing FlexibleInt</h3><pre>struct FlexibleInt: Decodable {<br>    let value: Int</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.singleValueContainer()</pre><pre>        if let value = try? container.decode(Int.self) {<br>            self.value = value<br>            return<br>        }</pre><pre>        if let string = try? container.decode(String.self),<br>           let value = Int(string) {<br>            self.value = value<br>            return<br>        }</pre><pre>        throw DecodingError.typeMismatch(<br>            Int.self,<br>            .init(<br>                codingPath: decoder.codingPath,<br>                debugDescription:<br>                    &quot;Expected an integer or numeric string&quot;<br>            )<br>        )<br>    }<br>}</pre><p>We can now use it in a model:</p><pre>struct User: Decodable {<br>    let id: FlexibleInt<br>}</pre><p>Both 123 and &quot;123&quot; can be decoded into the same logical integer value.</p><p>The wrapper provides an explicit compatibility rule.</p><p>It does <strong>not</strong> mean that every possible representation should be accepted.</p><p>For example, &quot;twelve&quot;, 12.5, and true should remain invalid unless the API contract explicitly defines how to interpret them.</p><p>This is an important architectural distinction: <strong>robust decoding means supporting known variations, not accepting arbitrary data.</strong></p><p>One additional design consideration: FlexibleInt is a wrapper type, so id becomes a FlexibleInt, not an Int. You can expose its underlying value or design a semantic ID type around it, depending on the needs of the application.</p><h3>4.5 Custom encode(to:)</h3><p>So far, we’ve focused on decoding. But sometimes the API expects a different representation when we send data back.</p><p>Suppose the application model is:</p><pre>struct User {<br>    let id: Int<br>}</pre><p>But the server expects this request:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;<br>}</pre><p>The application stores an integer, while the API expects a string.</p><p>We can implement custom encoding:</p><pre>struct User: Encodable {<br>    let id: Int</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case id<br>    }</pre><pre>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        try container.encode(<br>            String(id),<br>            forKey: .id<br>        )<br>    }<br>}</pre><p>Now:</p><pre>User(id: 123)</pre><p>encodes as:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;<br>}</pre><p>The key takeaway is that the Swift representation and the JSON representation don’t have to use the same type.</p><h3>4.6 Asymmetric Codable: Decoding and Encoding Can Differ</h3><p>This leads to a useful concept: <strong>asymmetric serialization</strong>.</p><p>A server might return:</p><pre>{<br>    &quot;id&quot;: 123<br>}</pre><p>but expect:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;<br>}</pre><p>The response and request representations differ even though they refer to the same logical ID.</p><p>This is perfectly valid.</p><p>Codable combines Decodable and Encodable, but that doesn&#39;t require the two directions to use identical representations.</p><p>However, there is an architectural question worth asking: should one model handle both directions?</p><p>For a simple case, custom decoding and encoding may be enough. For a more complex API, separate request and response DTOs can make the contract clearer.</p><p>For example:</p><ul><li>UserResponseDTO represents the server response.</li><li>CreateUserRequestDTO represents the request payload.</li><li>User represents the application&#39;s domain model.</li></ul><p>This avoids forcing a single type to represent different API contracts.</p><h3>4.7 Single-Value Containers</h3><p>A single-value container is useful when a custom type represents one JSON value rather than an object containing multiple properties.</p><p>Examples include:</p><pre>123</pre><pre>&quot;123&quot;</pre><pre>&quot;pending&quot;</pre><p>These values don’t have named fields that require a keyed container.</p><p>A single-value container lets you decode or encode the value directly.</p><h3>Example: UserID</h3><p>Instead of passing raw strings throughout the application:</p><pre>let id: String</pre><p>We can introduce a semantic type:</p><pre>struct UserID: Codable {<br>    let value: String</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.singleValueContainer()</pre><pre>        if let value = try? container.decode(String.self) {<br>            self.value = value<br>            return<br>        }</pre><pre>        if let value = try? container.decode(Int.self) {<br>            self.value = String(value)<br>            return<br>        }</pre><pre>        throw DecodingError.typeMismatch(<br>            String.self,<br>            .init(<br>                codingPath: decoder.codingPath,<br>                debugDescription:<br>                    &quot;Expected a string or integer ID&quot;<br>            )<br>        )<br>    }</pre><pre>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.singleValueContainer()<br>        try container.encode(value)<br>    }<br>}</pre><p>This type accepts either a string ID or an integer ID during decoding, but always encodes its value as a JSON string.</p><p>That behavior is intentional and asymmetric.</p><p>A semantic type such as UserID communicates what a value represents, while custom decoding defines which external representations are supported.</p><h3>4.8 Custom Decoding of Nested Structures</h3><p>Sometimes the API structure maps directly to the application’s model.</p><p>For example:</p><pre>{<br>    &quot;user&quot;: {<br>        &quot;id&quot;: 123,<br>        &quot;profile&quot;: {<br>            &quot;name&quot;: &quot;Khaled&quot;<br>        }<br>    }<br>}</pre><p>This can be represented with ordinary nested models:</p><pre>struct Response: Decodable {<br>    let user: User<br>}</pre><pre>struct User: Decodable {<br>    let id: Int<br>    let profile: Profile<br>}</pre><pre>struct Profile: Decodable {<br>    let name: String<br>}</pre><p>No custom decoding is necessary.</p><p>But what if the API provides:</p><pre>{<br>    &quot;user&quot;: {<br>        &quot;first_name&quot;: &quot;Khaled&quot;,<br>        &quot;last_name&quot;: &quot;Kamal&quot;<br>    }<br>}</pre><p>while the application wants a single property:</p><pre>struct User: Decodable {<br>    let fullName: String<br>}</pre><p>The application model requires a transformation that doesn’t map directly to a single JSON field.</p><p>We can implement custom decoding:</p><pre>struct User: Decodable {<br>    let fullName: String</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case firstName = &quot;first_name&quot;<br>        case lastName = &quot;last_name&quot;<br>    }</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        let firstName = try container.decode(<br>            String.self,<br>            forKey: .firstName<br>        )</pre><pre>        let lastName = try container.decode(<br>            String.self,<br>            forKey: .lastName<br>        )</pre><pre>        self.fullName = &quot;\(firstName) \(lastName)&quot;<br>    }<br>}</pre><p>The decoder combines two external fields into one property.</p><p>This is useful when the transformation is genuinely part of the model’s decoding responsibility.</p><p>However, if your application is adopting a DTO-to-domain architecture, this transformation may be better placed in a mapping layer. The correct choice depends on where you want API-specific logic to live.</p><h3>4.9 When Should You Avoid Custom Codable?</h3><p>Custom decoding is powerful, but more code doesn’t automatically mean better design.</p><p>If the JSON structure matches the Swift model, prefer synthesized conformance:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>Don’t implement init(from:) simply because you can.</p><p>Custom decoding or encoding is useful when you need:</p><ul><li>Type conversion.</li><li>Multiple supported representations.</li><li>Custom handling of missing or null values.</li><li>Validation of external representations.</li><li>Transformation of nested structures.</li><li>Nonstandard date formats.</li><li>Resilient handling of unknown enum values.</li><li>Polymorphic decoding.</li><li>Compatibility with legacy API contracts.</li></ul><p>Before implementing custom logic, ask yourself:</p><ol><li>Is this behavior actually required by the API contract?</li><li>Can synthesized decoding already handle it?</li><li>Should the transformation happen in a custom decoder or a mapping layer?</li><li>What should happen when the incoming value is invalid?</li><li>Can the behavior be tested independently?</li></ol><p>These questions help prevent custom Codable implementations from becoming difficult to understand and maintain.</p><h3>4.10 DTO vs. Domain Model</h3><p>This is where Codable connects directly to the application architecture.</p><p>Consider the following response:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;first_name&quot;: &quot;Khaled&quot;,<br>    &quot;last_name&quot;: &quot;Kamal&quot;,<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>We could try to represent it directly with a domain model:</p><pre>struct User: Codable {<br>    let id: Int<br>    let fullName: String<br>    let age: Int<br>}</pre><p>But the external representation doesn’t match the model. The API uses strings for numeric values, separates the name into two fields, and may have its own naming conventions.</p><p>One option is to handle all these differences with custom decoding. Another is to introduce a DTO.</p><h3>Step 1: Represent the API response</h3><pre>struct UserDTO: Decodable {<br>    let id: String<br>    let firstName: String<br>    let lastName: String<br>    let age: String</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case firstName = &quot;first_name&quot;<br>        case lastName = &quot;last_name&quot;<br>        case age<br>    }<br>}</pre><h3>Step 2: Define the domain model</h3><pre>struct User {<br>    let id: Int<br>    let fullName: String<br>    let age: Int<br>}</pre><h3>Step 3: Map the DTO into the domain model</h3><pre>enum UserMappingError: Error {<br>    case invalidID<br>    case invalidAge<br>}</pre><pre>extension UserDTO {<br>    func toDomain() throws -&gt; User {<br>        guard let id = Int(id) else {<br>            throw UserMappingError.invalidID<br>        }</pre><pre>        guard let age = Int(age) else {<br>            throw UserMappingError.invalidAge<br>        }</pre><pre>        return User(<br>            id: id,<br>            fullName: &quot;\(firstName) \(lastName)&quot;,<br>            age: age<br>        )<br>    }<br>}</pre><p>Now each component has a clearer responsibility:</p><p><strong>Codable</strong> handles serialization and deserialization.</p><p><strong>DTO</strong> represents the external API contract.</p><p><strong>Mapping</strong> transforms and validates API data for the application.</p><p><strong>Domain model</strong> represents concepts the application works with.</p><p>The separation becomes especially valuable when backend contracts change independently of application requirements.</p><p>It also introduces additional types and mapping code, so it isn’t necessary for every small model. Use the separation when it meaningfully reduces coupling or clarifies responsibilities.</p><h3>Level 4 Challenge: Design Before You Code</h3><p>Let’s bring these concepts together with a realistic API response.</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;Khaled&quot;,<br>    &quot;price&quot;: &quot;99.50&quot;,<br>    &quot;currency&quot;: &quot;USD&quot;,<br>    &quot;status&quot;: &quot;new_status&quot;,<br>    &quot;created_at&quot;: 1754656200000,<br>    &quot;metadata&quot;: null<br>}</pre><p>Your application model should be:</p><pre>struct Product {<br>    let id: ProductID<br>    let name: String<br>    let price: Decimal<br>    let currency: Currency<br>    let status: ProductStatus<br>    let createdAt: Date<br>    let metadata: Metadata?<br>}</pre><p>Before writing any implementation, make seven design decisions.</p><h3>1. Product ID</h3><p>The API returns:</p><pre>{<br>    &quot;id&quot;: 123<br>}</pre><p>Would you use Int or ProductID in the domain model?</p><p>Consider type safety, domain meaning, and whether a dedicated type provides enough value to justify the additional abstraction.</p><h3>2. Price</h3><p>The API returns:</p><pre>{<br>    &quot;price&quot;: &quot;99.50&quot;<br>}</pre><p>But the domain requires Decimal.</p><p>Where should the conversion happen: inside a custom decoder, inside the DTO, or during DTO-to-domain mapping?</p><p>Consider monetary precision, invalid values, and separation of responsibilities.</p><h3>3. Currency</h3><p>The API may return:</p><pre>USD<br>EUR<br>GBP<br>new_currency</pre><p>How should your model handle a currency the current app doesn’t recognize?</p><p>Should decoding fail, should an unknown value be preserved, or should the app substitute a default?</p><p>Think about the difference between successfully displaying a product and safely performing a financial operation.</p><h3>4. Product Status</h3><p>The known statuses are:</p><pre>pending<br>completed<br>cancelled</pre><p>But the backend might introduce:</p><pre>new_status</pre><p>How should ProductStatus behave when it encounters an unknown value?</p><p>Consider both forward compatibility and the business actions that should be allowed for unknown statuses.</p><h3>5. Creation Date</h3><p>The API returns:</p><pre>1754656200000</pre><p>What timestamp format does this most likely represent?</p><p>Where should the conversion to Date happen, and what could go wrong if the unit is interpreted incorrectly?</p><h3>6. Metadata</h3><p>The API returns:</p><pre>{<br>    &quot;metadata&quot;: null<br>}</pre><p>The application expects:</p><pre>let metadata: Metadata?</pre><p>How should this be decoded?</p><p>More importantly, should a missing metadata key mean the same thing as an explicit null? Your answer should depend on the API contract.</p><h3>7. Architecture</h3><p>Would you implement:</p><pre>Product: Codable</pre><p>or prefer:</p><pre>ProductDTO: Decodable<br>        ↓<br>      Mapping<br>        ↓<br>      Product</pre><p>Explain the trade-offs. Consider API complexity, domain independence, testability, and maintenance cost.</p><h3>Final Thoughts</h3><p>The real goal of Level 4 isn’t to memorize more Codable APIs. It&#39;s to develop the judgment to choose the right boundary for each responsibility.</p><p>A reliable implementation should make external data predictable without hiding invalid values, preserve important information when APIs evolve, and keep application models independent of backend quirks where that separation provides value.</p><p><strong>Your next step:</strong> Answer the seven design questions before writing any code. Review the trade-offs, challenge your assumptions, and only then implement the solution.</p><p>That is the difference between simply making JSONDecoder work on designing a decoding strategy that can survive production.</p><p><strong>Happy coding!</strong> 🚀</p><p>#Swift #iOSDevelopment #SwiftCodable #JSON #MobileDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a66478a23fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3 — Edge Cases & Dirty APIs: Mastering Swift Codable]]></title>
            <link>https://medium.com/@khaledkamal/part-3-edge-cases-dirty-apis-mastering-swift-codable-32a6fcd14b0b?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/32a6fcd14b0b</guid>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 12:27:52 GMT</pubDate>
            <atom:updated>2026-10-15T12:27:52.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9Sz5cEF00IndyfWM1Q_1w.jpeg" /></figure><p>In <a href="https://medium.com/@khaledkamal/part-2-practical-codable-mastering-swift-codable-be15a1cb013c">Part 2</a>, we explored how Swift Codable works, including nested objects, arrays, optionals, CodingKeys, dates, and custom decoding.</p><p>But real-world APIs aren’t always consistent.</p><p>Sometimes a backend returns an integer as a string. Sometimes a field is missing, an enum contains an unknown value, or an array contains an element that doesn’t match the expected model.</p><p>What happens then?</p><p>This is where we move from understanding <strong>how </strong><strong>Codable works</strong> to understand <strong>how to build resilient API decoding in production iOS applications</strong>.</p><p>In this article, we’ll explore:</p><ol><li>Missing keys vs. null</li><li>decode() vs. decodeIfPresent()</li><li>Unexpected data types</li><li>Flexible decoding for String and Int</li><li>Default values</li><li>Arrays containing invalid elements</li><li>Lossy decoding and its risks</li><li>Unknown enum values</li><li>Separating decoding from business validation</li><li>Designing models for messy API responses</li></ol><p>Let’s get started.</p><h3>3.1 Missing Key vs. null</h3><p>Consider this model:</p><pre>struct User: Codable {<br>    let name: String?<br>}</pre><p>Now imagine the backend returns one of these responses.</p><p><strong>Case 1: Missing key</strong></p><pre>{}</pre><p><strong>Case 2: Explicit </strong><strong>null</strong></p><pre>{<br>    &quot;name&quot;: null<br>}</pre><p><strong>Case 3: Empty string</strong></p><pre>{<br>    &quot;name&quot;: &quot;&quot;<br>}</pre><p><strong>Case 4: Actual value</strong></p><pre>{<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><p>With a synthesized Decodable Implementation, the results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRIEvbpMbpe5tOc2asGnSw.png" /></figure><p>An optional string preserves the difference between an empty string and nil, but it doesn&#39;t preserve the distinction between a missing key and an explicit null.</p><p>For many application models, this is perfectly acceptable.</p><p>However, consider a PATCH endpoint.</p><pre>{}</pre><p>might mean:</p><blockquote><em>Don’t modify the existing name.</em></blockquote><p>While:</p><pre>{<br>    &quot;name&quot;: null<br>}</pre><p>might mean:</p><blockquote><em>Remove the existing name.</em></blockquote><p>These are different business operations.</p><p>An ordinary String? cannot represent all three states independently. When that distinction matters, we can introduce a custom representation:</p><pre>enum Field&lt;Value&gt; {<br>    case missing<br>    case null<br>    case value(Value)<br>}</pre><p>We’ll explore the implementation of this pattern when we need it.</p><p><strong>The takeaway:</strong> Always understand what is missing and null mean in the API contract before deciding how to model an optional field.</p><h3>3.2 decode() vs. decodeIfPresent()</h3><p>This is one of the most important distinctions in Swift decoding.</p><h3>Using decode()</h3><pre>let name = try container.decode(<br>    String.self,<br>    forKey: .name<br>)</pre><p>This requires the key to exist and contain a valid, non-null string.</p><p>If the key is missing, decoding throws DecodingError.keyNotFound.</p><p>If the value is null, decoding fails because String cannot represent null.</p><h3>Using decodeIfPresent()</h3><pre>let name = try container.decodeIfPresent(<br>    String.self,<br>    forKey: .name<br>)</pre><p>This returns a String?.</p><p>JSON stateResult&quot;name&quot;: &quot;John&quot;&quot;John&quot;&quot;name&quot;: nullnilMissing namenil</p><p>The mental model is simple:</p><ul><li>decode() means the value is required.</li><li>decodeIfPresent() means the value may be missing or null.</li></ul><p>This distinction also explains why synthesized decoding normally handles an optional stored property differently from a non-optional property.</p><pre>struct User: Decodable {<br>    let name: String?<br>}</pre><p>Swift’s synthesized implementation uses the equivalent of decodeIfPresent() for this property.</p><p>For a required property:</p><pre>struct User: Decodable {<br>    let name: String<br>}</pre><p>Swift uses the equivalent of decode().</p><p>Understanding this behavior helps you decide when synthesized decoding is sufficient and when you need custom logic.</p><h3>3.3 What Happens When the Backend Sends the Wrong Type?</h3><p>Suppose your model expects an integer:</p><pre>struct User: Decodable {<br>    let age: Int<br>}</pre><p>The backend returns:</p><pre>{<br>    &quot;age&quot;: 25<br>}</pre><p>Everything works.</p><p>But what if the response is:</p><pre>{<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>Now decoding fails with a type mismatch.</p><p>Why?</p><p>Because JSONDecoder doesn&#39;t automatically convert every string containing digits into an integer.</p><p>Your model expects:</p><pre>Int</pre><p>But the JSON contains:</p><pre>String</pre><p>These are different types.</p><p>This is a common example of an inconsistent backend contract. It can happen when an API changes its response format, legacy endpoints behave differently, or multiple services return the same field in different representations.</p><p>The question is: should we make the decoder more flexible?</p><p>The answer depends on whether this variation is expected and acceptable.</p><h3>3.4 A Production Pattern: Flexible Integer Decoding</h3><p>Suppose the API is documented or observed to return either:</p><pre>{<br>    &quot;age&quot;: 25<br>}</pre><p>or:</p><pre>{<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>Instead of adding conversion logic throughout your application, create a reusable type.</p><pre>struct FlexibleInt: Codable {<br>    let value: Int</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.singleValueContainer()</pre><pre>        if let value = try? container.decode(Int.self) {<br>            self.value = value<br>            return<br>        }</pre><pre>        if let string = try? container.decode(String.self),<br>           let value = Int(string) {<br>            self.value = value<br>            return<br>        }</pre><pre>        throw DecodingError.typeMismatch(<br>            Int.self,<br>            .init(<br>                codingPath: decoder.codingPath,<br>                debugDescription:<br>                    &quot;Expected an Int or a String representing an Int.&quot;<br>            )<br>        )<br>    }</pre><pre>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.singleValueContainer()<br>        try container.encode(value)<br>    }<br>}</pre><p>Now update your model:</p><pre>struct User: Codable {<br>    let age: FlexibleInt<br>}</pre><p>Both of these responses can now be decoded:</p><pre>{<br>    &quot;age&quot;: 25<br>}</pre><pre>{<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>To access the integer:</p><pre>let age = user.age.value</pre><p>Notice that this implementation accepts valid integers represented as either JSON numbers or numeric strings. It still rejects values such as &quot;hello&quot;.</p><p>This keeps the flexibility explicit and localized instead of spreading conversion logic throughout the codebase.</p><h3>3.5 Why Do We Use singleValueContainer()?</h3><p>Look at the two possible representations of age:</p><pre>25</pre><p>and:</p><pre>&quot;25&quot;</pre><p>Both represent a single JSON value. Neither is an object with named keys nor an array of elements.</p><p>That’s why we use:</p><pre>let container = try decoder.singleValueContainer()</pre><p>This container allows us to attempt decoding the same value using different Swift types:</p><pre>container.decode(Int.self)</pre><p>or:</p><pre>container.decode(String.self)</pre><p>The broader lesson is that decoding containers corresponds to the shape of the data:</p><ul><li><strong>Objects </strong>use <strong>keyed containers</strong>.</li><li><strong>Arrays</strong> use <strong>unkeyed containers</strong>.</li><li><strong>Primitive</strong> values use <strong>single-value containers</strong>.</li></ul><p>Understanding this relationship makes custom decoding much easier to reason about.</p><h3>3.6 Don’t Overuse Flexible Decoding</h3><p>Flexible decoding is useful, but it shouldn’t become a way to hide backend bugs.</p><p>Suppose the API contract specifies:</p><pre>{<br>    &quot;age&quot;: 25<br>}</pre><p>Then the backend suddenly sends:</p><pre>{<br>    &quot;age&quot;: &quot;hello&quot;<br>}</pre><p>Should your app silently convert this to zero?</p><p>Absolutely not.</p><p>Consider these cases:</p><p>InputExpected behavior25Accept&quot;25&quot;Accept if this format is a known variation&quot;hello&quot;Reject as invalidnullAccept only if the contract permits it</p><p>A useful rule is:</p><p><strong>Handle known variations explicitly; don’t silently accept unexpected corruption.</strong></p><p>The goal isn’t to make decoding succeed at any cost. It’s to make the application tolerant of legitimate variations while still detecting invalid data.</p><h3>3.7 Default Values: A Common Codable Trap</h3><p>Consider this model:</p><pre>struct User: Decodable {<br>    let name: String = &quot;&quot;<br>}</pre><p>You might expect the following JSON to produce a user with an empty name:</p><pre>{}</pre><p>However, there is an important detail: a stored property initialized with a default value is not automatically treated as a fallback by synthesized decoding.</p><p>Because name has an initial value, Swift generally excludes it from the synthesized CodingKeys requirements for decoding. Consequently, the initial value can remain in place rather than being populated from the JSON.</p><p>This becomes particularly confusing when developers expect a default to be used only when the server omits the field.</p><p>If you need explicit fallback behavior, implement it intentionally.</p><h3>The safer approach</h3><pre>struct User: Decodable {<br>    let name: String</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case name<br>    }</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        name = try container.decodeIfPresent(<br>            String.self,<br>            forKey: .name<br>        ) ?? &quot;&quot;<br>    }<br>}</pre><p>Now both of these responses produce an empty string:</p><pre>{}</pre><pre>{<br>    &quot;name&quot;: null<br>}</pre><p>But this response preserves its actual value:</p><pre>{<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><p>The important point is that decodeIfPresent() returns nil for both missing and null values, so the fallback applies to both.</p><p><strong>Default values are a business decision, not a universal decoding rule.</strong></p><p>Use a fallback only when it makes sense for the field and the API contract.</p><p>For example, a missing display name might reasonably become an empty string, while a missing account identifier should probably remain a decoding error.</p><h3>3.8 Arrays Containing Invalid Elements</h3><p>Now consider a response containing users:</p><pre>{<br>    &quot;users&quot;: [<br>        {<br>            &quot;id&quot;: 1<br>        },<br>        null,<br>        {<br>            &quot;id&quot;: 3<br>        }<br>    ]<br>}</pre><p>And these models:</p><pre>struct User: Decodable {<br>    let id: Int<br>}</pre><pre>struct Response: Decodable {<br>    let users: [User]<br>}</pre><p>Decoding fails because the second element is null, not a User.</p><p>The type:</p><pre>[User]</pre><p>means every element must successfully decode as a User.</p><p>One invalid element can cause the entire array to fail.</p><p>But what if the API contract explicitly allows null elements?</p><h3>3.9 When Null Elements Are Valid</h3><p>In that case, the model can reflect the API’s actual structure:</p><pre>struct Response: Decodable {<br>    let users: [User?]<br>}</pre><p>Now the array can represent:</p><pre>[<br>    User(id: 1),<br>    nil,<br>    User(id: 3)<br>]</pre><p>This is appropriate when null elements have a legitimate meaning.</p><p>However, changing [User] to [User?] doesn&#39;t make arbitrary invalid objects acceptable.</p><p>For example:</p><pre>{<br>    &quot;users&quot;: [<br>        {<br>            &quot;id&quot;: 1<br>        },<br>        {<br>            &quot;id&quot;: &quot;INVALID&quot;<br>        },<br>        {<br>            &quot;id&quot;: 3<br>        }<br>    ]<br>}</pre><p>The second element still fails because &quot;INVALID&quot; cannot decode as an Int.</p><p>This leads to another strategy: lossy decoding.</p><h3>3.10 Lossy Decoding: Skipping Invalid Elements</h3><p>Sometimes the API returns a collection where individual elements can fail independently, but the remaining elements are still useful.</p><p>For example, a recommendation feed might contain one malformed item among dozens of valid ones.</p><p>In such cases, you may choose to skip invalid elements instead of failing the entire array.</p><p>A reusable implementation is:</p><pre>struct LossyArray&lt;Element: Decodable&gt;: Decodable {<br>    let elements: [Element]</pre><pre>    init(from decoder: Decoder) throws {<br>        var container = try decoder.unkeyedContainer()<br>        var result: [Element] = []</pre><pre>        while !container.isAtEnd {<br>            do {<br>                let element = try container.decode(Element.self)<br>                result.append(element)<br>            } catch {<br>                // Consume the invalid element before continuing.<br>                _ = try container.superDecoder()<br>            }<br>        }</pre><pre>        elements = result<br>    }<br>}</pre><p>You can then use it in your response model:</p><pre>struct Response: Decodable {<br>    let users: LossyArray&lt;User&gt;<br>}</pre><p>Access the successfully decoded users through:</p><pre>response.users.elements</pre><p>The key detail is that a failed element must be consumed before decoding continues. Otherwise, the decoder can remain positioned at the same element and repeatedly encounter the same failure.</p><p>For production use, this approach should also be tested against malformed nested data and decoding errors to ensure that the collection advances correctly.</p><h3>3.11 Lossy Decoding Can Be Dangerous</h3><p>Consider a financial response:</p><pre>{<br>    &quot;transactions&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;amount&quot;: 100<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;amount&quot;: &quot;CORRUPTED&quot;<br>        }<br>    ]<br>}</pre><p>If you silently discard the second transaction, the UI may show only the first transaction.</p><p>That doesn’t mean the actual total is 100. It means only one transaction was successfully decoded.</p><p>This can be dangerous because the application may present incomplete data as if it were complete.</p><h3>Where might lossy decoding be appropriate?</h3><ul><li>Recommendation feeds</li><li>Non-critical UI content</li><li>Optional analytics events</li><li>Content collections where individual entries can be skipped safely</li></ul><h3>Where should you be cautious?</h3><ul><li>Payments and financial transactions</li><li>Account balances</li><li>Permissions and access-control data</li><li>Security configuration</li><li>Critical business operations</li></ul><p>The correct strategy depends on the consequences of losing an element.</p><p><strong>Senior-level engineering isn’t about making decoding never fail. It’s about choosing when failure is safer than silently accepting incomplete data.</strong></p><p>If you use lossy decoding, consider logging skipped elements and reporting decoding failures to your monitoring system.</p><h3>3.12 Unknown Enum Values</h3><p>Suppose your backend returns an order status:</p><pre>{<br>    &quot;status&quot;: &quot;pending&quot;<br>}</pre><p>You model it using a raw-value enum:</p><pre>enum Status: String, Codable {<br>    case pending<br>    case completed<br>}</pre><p>This works until the backend introduces another status:</p><pre>{<br>    &quot;status&quot;: &quot;processing&quot;<br>}</pre><p>Because &quot;processing&quot; It isn&#39;t one of the declared cases; synthesized decoding fails.</p><p>This can make your application unnecessarily fragile when the backend adds new values.</p><p>A forward-compatible approach is to preserve unknown values explicitly.</p><pre>enum Status: Codable {<br>    case pending<br>    case completed<br>    case unknown(String)</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.singleValueContainer()<br>        let rawValue = try container.decode(String.self)</pre><pre>        switch rawValue {<br>        case &quot;pending&quot;:<br>            self = .pending</pre><pre>        case &quot;completed&quot;:<br>            self = .completed</pre><pre>        default:<br>            self = .unknown(rawValue)<br>        }<br>    }</pre><pre>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.singleValueContainer()</pre><pre>        switch self {<br>        case .pending:<br>            try container.encode(&quot;pending&quot;)</pre><pre>        case .completed:<br>            try container.encode(&quot;completed&quot;)</pre><pre>        case .unknown(let value):<br>            try container.encode(value)<br>        }<br>    }<br>}</pre><p>Now:</p><pre>{<br>    &quot;status&quot;: &quot;processing&quot;<br>}</pre><p>becomes:</p><pre>Status.unknown(&quot;processing&quot;)</pre><p>Your application can continue operating while preserving the original value.</p><p>For example, the UI might display a generic status label for unknown values rather than crashing or rejecting the entire response.</p><p>This is particularly useful when the backend and mobile application don’t always deploy at the same time.</p><p>One important distinction: an unknown string is different from a missing or null status. If the field is required, those cases should still be handled according to the API contract.</p><h3>3.13 A Production Decoding Architecture</h3><p>At this point, we’ve explored several ways to handle imperfect API responses. The next step is understanding where decoding fits into the larger application architecture.</p><p>A useful mental model is:</p><p><strong>Backend → JSON → Decoding → Validation → Domain Model</strong></p><p>Each stage has a different responsibility.</p><h3>Decoding</h3><p>Answers:</p><blockquote><em>Can I transform this external representation into a Swift value?</em></blockquote><h3>Validation</h3><p>Answers:</p><blockquote><em>Is the decoded value acceptable for my application?</em></blockquote><p>Consider:</p><pre>{<br>    &quot;age&quot;: -500<br>}</pre><p>This value can be successfully decoded into an Int.</p><p>However, your business rules may reject it.</p><p>The problem isn’t the JSON type. The problem is the meaning of the value.</p><p>Likewise, a string might decode successfully but violate a domain constraint, or a status might be syntactically valid but unsupported for a particular operation.</p><p>Separating decoding from validation helps keep API-specific behavior out of your core business logic.</p><p>A practical architecture might look like this:</p><pre>Backend<br>   |<br>   v<br>JSON Data<br>   |<br>   v<br>JSONDecoder<br>   |<br>   v<br>API DTO<br>   |<br>   v<br>Validation / Mapping<br>   |<br>   v<br>Domain Model<br>   |<br>   v<br>Application</pre><p>The API DTO represents the external response. The domain model represents what your application needs to work with.</p><p>Not every project requires separate DTOs and domain models for every endpoint, but the separation becomes increasingly valuable as the application grows and API inconsistencies accumulate.</p><h3>3.14 A Senior-Level Example: Analyze Before You Decode</h3><p>Consider this API response:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;created_at&quot;: 1754656200000,<br>    &quot;status&quot;: &quot;future_status&quot;,<br>    &quot;profile&quot;: null,<br>    &quot;tags&quot;: [],<br>    &quot;metadata&quot;: {<br>        &quot;premium&quot;: true,<br>        &quot;score&quot;: &quot;98.5&quot;<br>    },<br>    &quot;items&quot;: [<br>        {<br>            &quot;id&quot;: 1<br>        },<br>        null,<br>        {<br>            &quot;id&quot;: &quot;3&quot;<br>        }<br>    ]<br>}</pre><p>Before writing any Swift code, inspect the structure and identify the potential edge cases.</p><p>Field Observation Question to resolveidString representation of an identifier. Should it remain a string?created_atNumeric timestamp in milliseconds. Which date strategy or conversion is required?statusUnknown enum value. Should unknown values be preserved?profileExplicit nullIs the profile optional?tagsIs an empty collection valid?metadata.premiumBoolean: Can it be decoded directly?metadata.scoreNumeric-looking string. Should it remain a string or become a number?itemsMixed object and null elements. Are nulls valid, and what should happen to malformed items?</p><p>Notice that we haven’t started coding yet.</p><p>We’re identifying the API contract, expected Swift types, and failure scenarios first.</p><p>This is an important habit to develop when working with real-world APIs.</p><p>Don’t automatically make every field optional or every decoder flexible. First, determine which variations are valid, which are legacy behavior, and which indicate a genuine error.</p><h3>3.15 Your Level 3 Challenge</h3><p>Now let’s put these concepts together.</p><p>Consider this response:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;name&quot;: null,<br>    &quot;age&quot;: &quot;25&quot;,<br>    &quot;status&quot;: &quot;processing&quot;,<br>    &quot;tags&quot;: [<br>        &quot;ios&quot;,<br>        null,<br>        &quot;swift&quot;<br>    ],<br>    &quot;items&quot;: [<br>        {<br>            &quot;id&quot;: 1<br>        },<br>        {<br>            &quot;id&quot;: &quot;2&quot;<br>        },<br>        null,<br>        {<br>            &quot;id&quot;: &quot;invalid&quot;<br>        }<br>    ]<br>}</pre><p>Don’t write the implementation yet. First, make the design decisions.</p><p><strong>1. Identifier</strong></p><p>What type would you choose for id? Would you keep it as a String, or convert it to an integer?</p><p><strong>2. Optional name</strong></p><p>What should happen when name is explicitly null? Is String? sufficient, or do you need to distinguish missing from null?</p><p><strong>3. Flexible integer</strong></p><p>The age field is a string. Would you use String, Int, or a custom FlexibleInt type?</p><p><strong>4. Unknown status</strong></p><p>How would you model &quot;processing&quot; When the app doesn&#39;t recognize that status?</p><p><strong>5. Nullable tags</strong></p><p>Would you choose [String], [String?], or another representation?</p><p><strong>6. Null item</strong></p><p>Should the null element in items be preserved, skipped, or treated as an error?</p><p><strong>7. Invalid identifier</strong></p><p>What should happen when an item contains &quot;id&quot;: &quot;invalid&quot;?</p><p><strong>8. Strict vs. lossy decoding</strong></p><p>Would you reject the entire collection or skip invalid elements? Explain your reasoning.</p><p><strong>9. Business validation</strong></p><p>Which checks belong in decoding, and which belong in the domain layer?</p><p>There isn’t necessarily one correct design for every API. The important thing is to justify your decisions based on the API contract and the consequences of accepting or rejecting the data.</p><p><strong>Try the exercise first.</strong> I’ll review your decisions from a senior iOS engineering perspective, and then we’ll build the models and decoding strategies step by step.</p><h3>Final Thoughts</h3><p>Working with Codable In production is about much more than making JSON decoding succeed.</p><p>It’s about understanding the difference between valid data, known variations, unknown values, and corrupted responses.</p><p>The principles to remember are:</p><ul><li><strong>Be strict by default.</strong> Don’t hide unexpected backend errors.</li><li><strong>Handle known variations intentionally.</strong> Use flexible types only where they’re justified.</li><li><strong>Preserve meaningful information.</strong> Don’t collapse distinct API states without understanding their semantics.</li><li><strong>Use lossy decoding carefully.</strong> Skipping invalid data can be more dangerous than rejecting it.</li><li><strong>Support forward compatibility.</strong> Unknown enum values don’t always need to break the application.</li><li><strong>Separate decoding from validation.</strong> A value can be valid Swift data but invalid for your business.</li></ul><p>The goal isn’t to build the most complicated decoder. It’s to build the simplest decoder that correctly reflects the API contract and protects your application from unexpected data.</p><p><strong>In the next part, we’ll continue exploring production-grade Codable patterns and how to build reliable API models for real-world iOS applications.</strong></p><p>If you’re working with inconsistent APIs, share the most challenging decoding issue you’ve encountered. I’d love to hear how you handled it.</p><p><strong>Happy coding!</strong> 🚀</p><p>#Swift #iOSDevelopment #SwiftCodable #JSON #MobileDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a6fcd14b0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2— Practical Codable: Mastering Swift Codable]]></title>
            <link>https://medium.com/@khaledkamal/part-2-practical-codable-mastering-swift-codable-be15a1cb013c?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/be15a1cb013c</guid>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 12:27:35 GMT</pubDate>
            <atom:updated>2026-10-15T12:27:35.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9Sz5cEF00IndyfWM1Q_1w.jpeg" /></figure><p>We’ll cover this progression:</p><pre>1. Nested objects<br>2. Arrays<br>3. Optionals<br>4. Missing vs null<br>5. CodingKeys<br>6. Key decoding strategies<br>7. Dates<br>8. Enums<br>9. Dictionaries<br>10. Real-world API modeling</pre><p>Today, let’s start with the most important part: <strong>nested objects + arrays + optionals</strong>.</p><h3>2.1 Nested Objects</h3><p>Consider:</p><pre>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;profile&quot;: {<br>    &quot;city&quot;: &quot;Cairo&quot;,<br>    &quot;country&quot;: &quot;Egypt&quot;<br>  }<br>}</pre><p>A natural Swift model is:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    let profile: Profile<br>}</pre><pre>struct Profile: Codable {<br>    let city: String<br>    let country: String<br>}</pre><p>And that’s enough.</p><pre>let user = try JSONDecoder().decode(User.self, from: data)</pre><p>Because both User and Profile conform to Codable, Swift can recursively synthesize the implementation.</p><h3>What’s actually happening?</h3><p>Think:</p><pre>User<br> │<br> ├── id → Int<br> │<br> ├── name → String<br> │<br> └── profile → Profile<br>                  │<br>                  ├── city → String<br>                  └── country → String</pre><p>At the root:</p><pre>JSON object<br>     ↓<br>KeyedDecodingContainer&lt;User.CodingKeys&gt;</pre><p>Then:</p><pre>&quot;profile&quot;<br>     ↓<br>Profile<br>     ↓<br>KeyedDecodingContainer&lt;Profile.CodingKeys&gt;</pre><p>So nested objects simply cause <strong>another decoding operation</strong>.</p><h3>2.2 Explicitly decoding nested objects</h3><p>You can manually write:</p><pre>struct User: Decodable {<br>    let id: Int<br>    let name: String<br>    let profile: Profile</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case name<br>        case profile<br>    }</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        id = try container.decode(Int.self, forKey: .id)<br>        name = try container.decode(String.self, forKey: .name)<br>        profile = try container.decode(Profile.self, forKey: .profile)<br>    }<br>}</pre><p>The important line:</p><pre>profile = try container.decode(<br>    Profile.self,<br>    forKey: .profile<br>)</pre><p>You don’t have to manually create another container.</p><p>Profile.self tells Codable:</p><blockquote><em>“Now decode a </em><em>Profile from the value associated with </em><em>profile.&quot;</em></blockquote><p>Then Profile.init(from:) takes over.</p><h3>2.3 When do we use nestedContainer()?</h3><p>You <strong>can</strong> manually access the nested container:</p><pre>let profileContainer = try container.nestedContainer(<br>    keyedBy: Profile.CodingKeys.self,<br>    forKey: .profile<br>)</pre><p>Then:</p><pre>let city = try profileContainer.decode(<br>    String.self,<br>    forKey: .city<br>)</pre><p>But normally, this is unnecessary.</p><p>Prefer:</p><pre>let profile = try container.decode(<br>    Profile.self,<br>    forKey: .profile<br>)</pre><h3>Production recommendation</h3><p>Use normal recursive decode() by default.</p><p>Use nestedContainer() When you need to inspect/manipulate the nested structure yourself.</p><h3>2.4 Arrays</h3><p>Now:</p><pre>{<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;tags&quot;: [<br>    &quot;ios&quot;,<br>    &quot;swift&quot;,<br>    &quot;architecture&quot;<br>  ]<br>}</pre><p>Model:</p><pre>struct User: Codable {<br>    let name: String<br>    let tags: [String]<br>}</pre><p>That’s it.</p><p>Codable automatically understands:</p><pre>[String]</pre><h3>Array of objects</h3><pre>{<br>  &quot;users&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;name&quot;: &quot;John&quot;<br>    },<br>    {<br>      &quot;id&quot;: 2,<br>      &quot;name&quot;: &quot;Mike&quot;<br>    }<br>  ]<br>}</pre><p>Model:</p><pre>struct Response: Codable {<br>    let users: [User]<br>}</pre><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>Again, Codable recursively decodes:</p><pre>Response<br>   │<br>   └── users<br>         ↓<br>    [User]<br>      │<br>      ├── User<br>      └── User</pre><h3>2.5 Manually decoding an array</h3><p>Now, let’s understand what happens internally.</p><pre>struct Response: Decodable {<br>    let users: [User]</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case users<br>    }</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        users = try container.decode(<br>            [User].self,<br>            forKey: .users<br>        )<br>    }<br>}</pre><p>Conceptually:</p><pre>Keyed container<br>      │<br>      │ &quot;users&quot;<br>      ▼<br>Unkeyed container<br>      │<br>      ├── User<br>      │     ├── id<br>      │     └── name<br>      │<br>      └── User<br>            ├── id<br>            └── name</pre><p>So [User].self triggers the array&#39;s own Decodable implementation.</p><h3>2.6 Optionals — VERY important</h3><p>Consider:</p><pre>struct User: Codable {<br>    let name: String?<br>}</pre><p>This means:</p><blockquote><em>The value may be absent.</em></blockquote><p>There are actually several possible API states:</p><h3>Value exists</h3><pre>{<br>  &quot;name&quot;: &quot;John&quot;<br>}</pre><p>Result:</p><pre>name == &quot;John&quot;</pre><h3>Explicit null</h3><pre>{<br>  &quot;name&quot;: null<br>}</pre><p>Result:</p><pre>name == nil</pre><h3>Key doesn’t exist</h3><pre>{}</pre><p>For a synthesized optional property, the decoder treats the missing value as nil.</p><p>Result:</p><pre>name == nil</pre><p>But this is <strong>not</strong> the same behavior as:</p><pre>let name: String</pre><h3>2.7 decode() vs decodeIfPresent()</h3><p>This distinction is critical.</p><p>Suppose:</p><pre>let name = try container.decode(<br>    String.self,<br>    forKey: .name<br>)</pre><p>This means:</p><blockquote><em>“The key must exist and contain a valid String.”</em></blockquote><p>If the key is missing:</p><pre>{}</pre><p>You get:</p><pre>DecodingError.keyNotFound</pre><p>If:</p><pre>{<br>  &quot;name&quot;: null<br>}</pre><p>You get a decoding failure because a non-optional String cannot represent null.</p><p>Now:</p><pre>let name = try container.decodeIfPresent(<br>    String.self,<br>    forKey: .name<br>)</pre><p>means:</p><blockquote><em>“The key may be missing or null. If there is a value, decode it.”</em></blockquote><p>Therefore:</p><pre>JSON                  decodeIfPresent<br>─────────────────────────────────────<br>&quot;name&quot;: &quot;John&quot;        &quot;John&quot;<br>&quot;name&quot;: null          nil<br>missing &quot;name&quot;        nil</pre><p>This is one of the most important Codable concepts.</p><h3>2.8 Why does synthesis use decodeIfPresent for optionals?</h3><p>For:</p><pre>struct User: Decodable {<br>    let name: String?<br>}</pre><p>Swift conceptually generates something like:</p><pre>name = try container.decodeIfPresent(<br>    String.self,<br>    forKey: .name<br>)</pre><p>Whereas:</p><pre>struct User: Decodable {<br>    let name: String<br>}</pre><p>is conceptually:</p><pre>name = try container.decode(<br>    String.self,<br>    forKey: .name<br>)</pre><p>This is why:</p><pre>String?</pre><p>has different decoding semantics.</p><h3>2.9 contains()</h3><p>Sometimes you need to distinguish:</p><pre>{}</pre><p>from:</p><pre>{<br>  &quot;name&quot;: null<br>}</pre><p>You can inspect:</p><pre>if container.contains(.name) {<br>    // Key exists<br>} else {<br>    // Key is missing<br>}</pre><p>Then:</p><pre>if container.contains(.name) {<br>    let name = try container.decodeIfPresent(<br>        String.self,<br>        forKey: .name<br>    )</pre><pre>    // nil here means the key existed but was null<br>}</pre><p>So:</p><pre>&quot;name&quot;?<br>                         /     \<br>                       NO       YES<br>                       │         │<br>                   missing     null/value?<br>                                 /    \<br>                               null   value</pre><p>This distinction becomes very important when dealing with PATCH APIs and backend semantics.</p><h3>2.10 Empty String ≠ Null ≠ Missing</h3><p>This is another important concept to understand when working with APIs.</p><p>Although these JSON responses may look similar, they represent <strong>four different API states</strong>:</p><p><strong>1. Missing key</strong></p><pre>{}</pre><p><strong>2. Explicit </strong><strong>null</strong></p><pre>{<br>  &quot;name&quot;: null<br>}</pre><p><strong>3. Empty string</strong></p><pre>{<br>  &quot;name&quot;: &quot;&quot;<br>}</pre><p><strong>4. Non-empty string</strong></p><pre>{<br>  &quot;name&quot;: &quot;John&quot;<br>}</pre><h4>The Difference in Swift</h4><p>When using a regular optional property:</p><pre>struct User: Decodable {<br>    let name: String?<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBJQ72qvTjwHHXPPCpCFmw.png" /></figure><p>The decoded results are:</p><p><strong>The limitation:</strong> An ordinary String? cannot distinguish between a missing key and an explicit null after decoding. However, it preserves the difference between nil and an empty string.</p><h4>What if We Need to Distinguish Missing from Null?</h4><p>If your business logic needs to handle missing and null differently, you need a custom representation.</p><p>For example:</p><pre>enum Field&lt;Value&gt; {<br>    case missing<br>    case null<br>    case value(Value)<br>}</pre><p>This enum explicitly represents all three states:</p><ul><li>.missing — The key doesn&#39;t exist in the JSON.</li><li>.null — The key exists, but its value is null.</li><li>.value(Value) — The key contains a value, including an empty string.</li></ul><h4>Full Decoding Example: name</h4><p>Let’s implement custom decoding directly in the model.</p><pre>enum Field&lt;Value&gt; {<br>    case missing<br>    case null<br>    case value(Value)<br>}</pre><pre>struct User: Decodable {<br>    let name: Field&lt;String&gt;</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case name<br>    }</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        if !container.contains(.name) {<br>            name = .missing<br>        } else if try container.decodeNil(forKey: .name) {<br>            name = .null<br>        } else {<br>            name = .value(<br>                try container.decode(String.self, forKey: .name)<br>            )<br>        }<br>    }<br>}</pre><h4>Decoding Results</h4><p>JSONDecoded</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POrJRTOKjhhdnXFItwzBHw.png" /></figure><h4>Key Takeaway</h4><p><strong>Empty string ≠ Null ≠ Missing.</strong></p><ul><li>Use String? when missing and null can be treated identically.</li><li>Use Field&lt;Value&gt; when your business logic needs to distinguish between missing, null, and an actual value.</li></ul><p>We will explore custom field representations in more detail later.</p><h3>2.11 CodingKeys</h3><p>Now imagine the backend sends:</p><pre>{<br>  &quot;user_id&quot;: 123,<br>  &quot;display_name&quot;: &quot;John&quot;<br>}</pre><p>But your Swift naming convention is:</p><pre>struct User: Codable {<br>    let userID: Int<br>    let displayName: String<br>}</pre><p>You can explicitly map:</p><pre>struct User: Codable {<br>    let userID: Int<br>    let displayName: String</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case userID = &quot;user_id&quot;<br>        case displayName = &quot;display_name&quot;<br>    }<br>}</pre><p>Now:</p><pre>Swift                  JSON<br>──────────────────────────────<br>userID          ←→     user_id<br>displayName     ←→     display_name</pre><h3>2.12 Ignoring properties</h3><p>Suppose:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    let isSelected: Bool<br>}</pre><p>But:</p><pre>isSelected</pre><p>It is purely a UI state and should <strong>not</strong> be encoded/decoded.</p><p>You can omit it from CodingKeys:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    var isSelected = false</pre><pre>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case name<br>    }<br>}</pre><p>Now Codable only deals with:</p><pre>id<br>name</pre><p>and ignores:</p><pre>isSelected</pre><p>This is very useful when a model contains local/application state.</p><h3>2.13 Key decoding strategy</h3><p>Instead of writing:</p><pre>enum CodingKeys: String, CodingKey {<br>    case userID = &quot;user_id&quot;<br>    case displayName = &quot;display_name&quot;<br>}</pre><p>You can configure:</p><pre>let decoder = JSONDecoder()<br>decoder.keyDecodingStrategy = .convertFromSnakeCase</pre><p>Then:</p><pre>{<br>  &quot;user_id&quot;: 123,<br>  &quot;display_name&quot;: &quot;John&quot;<br>}</pre><p>can map to:</p><pre>struct User: Codable {<br>    let userId: Int<br>    let displayName: String<br>}</pre><p>However, <strong>don’t blindly use </strong><strong>.convertFromSnakeCase everywhere</strong>.</p><p>There are edge cases involving acronyms, unusual capitalization, and keys such as:</p><pre>URL_value<br>user_ID<br>some__value</pre><p>We’ll go deeply into its exact conversion rules next.</p><h3>2.14 Dates</h3><p>JSON doesn’t have a native Date type.</p><p>So this:</p><pre>{<br>  &quot;created_at&quot;: &quot;2026-08-10T12:30:00Z&quot;<br>}</pre><p>requires a decoding strategy.</p><p>For ISO 8601:</p><pre>let decoder = JSONDecoder()<br>decoder.dateDecodingStrategy = .iso8601</pre><p>Then:</p><pre>struct User: Codable {<br>    let createdAt: Date<br>}</pre><p>For Unix seconds:</p><pre>{<br>  &quot;createdAt&quot;: 1754656200<br>}</pre><p>use:</p><pre>decoder.dateDecodingStrategy = .secondsSince1970</pre><p>For milliseconds:</p><pre>decoder.dateDecodingStrategy = .millisecondsSince1970</pre><p>The important architectural point:</p><blockquote><strong><em>The model says </em></strong><strong><em>Date; the decoder configuration determines how the external representation becomes a </em></strong><strong><em>Date.</em></strong></blockquote><h3>2.15 Enums</h3><p>Simple backend enum:</p><pre>{<br>  &quot;status&quot;: &quot;pending&quot;<br>}</pre><p>Swift:</p><pre>enum Status: String, Codable {<br>    case pending<br>    case completed<br>}</pre><p>Then:</p><pre>struct Order: Codable {<br>    let status: Status<br>}</pre><p>But what if tomorrow the backend sends:</p><pre>{<br>  &quot;status&quot;: &quot;processing&quot;<br>}</pre><p>And your app doesn’t know about &quot;processing&quot;?</p><p>Synthesized decoding fails.</p><p>This is why production APIs often need an unknown case:</p><pre>enum Status: Codable {<br>    case pending<br>    case completed<br>    case unknown(String)</pre><pre>    init(from decoder: Decoder) throws {<br>        let container = try decoder.singleValueContainer()<br>        let value = try container.decode(String.self)</pre><pre>        switch value {<br>        case &quot;pending&quot;:<br>            self = .pending<br>        case &quot;completed&quot;:<br>            self = .completed<br>        default:<br>            self = .unknown(value)<br>        }<br>    }<br>}</pre><p>Notice something important:</p><p><strong>An enum represented by a JSON string uses a </strong><strong>SingleValueDecodingContainer.</strong></p><p>That’s a great example of our container mental model.</p><h3>The mental model for Level 2</h3><p>When you see an API response, don’t immediately write Swift properties.</p><p>First, analyze the shape:</p><pre>JSON<br> │<br> ├── Object<br> │     └── Keyed container<br> │<br> ├── Array<br> │     └── Unkeyed container<br> │<br> └── Primitive / single value<br>       └── Single-value container</pre><p>Then recursively analyze what’s inside.</p><p>For:</p><pre>{<br>  &quot;user&quot;: {<br>    &quot;id&quot;: 123,<br>    &quot;tags&quot;: [&quot;ios&quot;, &quot;swift&quot;],<br>    &quot;status&quot;: &quot;active&quot;<br>  }<br>}</pre><p>You should mentally see:</p><pre>Root<br>└── Object → Keyed<br>      │<br>      └── user<br>            │<br>            ▼<br>          Object → Keyed<br>            │<br>            ├── id<br>            │     └── Single value → Int<br>            │<br>            ├── tags<br>            │     └── Array → Unkeyed<br>            │           ├── String<br>            │           └── String<br>            │<br>            └── status<br>                  └── Single value → String</pre><p>That’s the foundation we’re going to use for the difficult cases.</p><h3>Your Level 2 Exercise</h3><p>Don’t write code yet.</p><p>Given this API response:</p><pre>{<br>  &quot;id&quot;: &quot;123&quot;,<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;profile&quot;: {<br>    &quot;city&quot;: &quot;Cairo&quot;<br>  },<br>  &quot;tags&quot;: [<br>    &quot;ios&quot;,<br>    &quot;swift&quot;<br>  ],<br>  &quot;status&quot;: &quot;new_status&quot;<br>}</pre><p>Tell me:</p><h3>1. What Swift types would you choose for:</h3><pre>id       → ?<br>name     → ?<br>profile  → ?<br>tags     → ?<br>status   → ?</pre><h3>2. Which fields can be decoded automatically?</h3><h3>3. Which field requires custom decoding?</h3><h3>4. Which containers are involved?</h3><p>Try to answer first. <strong>I won’t give you the solution yet.</strong></p><p>After your answer, we’ll tackle <strong>Level 2.2 — inconsistent backend types (</strong><strong>String vs </strong><strong>Int), robust enums, dates, and the first production-grade Codable patterns.</strong></p><h3>Final Thoughts</h3><p>Understanding Swift Codable It is not just about converting JSON into Swift models. It’s about understanding how Swift interprets the structure, types, and edge cases of real-world API responses.</p><p>The key is to stop treating decoding as magic and start understanding what happens behind the scenes:</p><ul><li><strong>Objects</strong> → KeyedDecodingContainer</li><li><strong>Arrays</strong> → UnkeyedDecodingContainer</li><li><strong>Primitive values</strong> → SingleValueDecodingContainer</li><li><strong>Optional fields</strong> → Understand the difference between missing keys and null.</li><li><strong>Custom decoding</strong> → Use it when the backend’s behavior requires more control than synthesized conformance provides.</li></ul><p>Once you understand these fundamentals, handling inconsistent API responses, custom date formats, unknown enum values, and complex nested models becomes much easier.</p><p><strong>My goal with this series is to go beyond simply using </strong><strong>Codable and understanding how it actually works in production iOS applications.</strong></p><h3>Before Moving to <a href="https://medium.com/@khaledkamal/part-3-edge-cases-dirty-apis-mastering-swift-codable-32a6fcd14b0b">Part 3</a></h3><p>You’ve now explored some of the most common challenges developers face when working with real-world APIs: inconsistent types, unexpected enum values, date formats, and the need to make decoding more resilient.</p><p>The important lesson is that <strong>your Swift models should represent the data your application expects, while your decoding logic should handle the differences between that expectation and what the backend actually sends.</strong></p><p>You don’t need custom decoding for every property. Synthesized Codable is often the best starting point. Introduce custom logic when the API&#39;s structure, inconsistent types, or business requirements demand it.</p><p>Before moving on, think about how you would handle these situations in a production application:</p><ul><li>An API returns &quot;123&quot; instead of 123.</li><li>A backend introduces a new enum value after your app has been released.</li><li>A date arrives in a different format than expected.</li><li>One endpoint returns a field as a string, while another returns the same field as a number.</li></ul><p>Would your current models handle these cases gracefully, or would decoding fail?</p><h3>Let’s Discuss</h3><p>How do you design your API models to handle unexpected backend changes?</p><p>Do you prefer strict decoding that exposes invalid responses immediately, or more flexible decoding that allows the application to continue when possible?</p><p>Share your approach in the comments. I’d love to hear how other iOS developers balance reliability, flexibility, and maintainability.</p><p>In<a href="https://medium.com/@khaledkamal/part-3-edge-cases-dirty-apis-mastering-swift-codable-32a6fcd14b0b"> <strong>Part 3</strong></a><strong> of the <em>Mastering Swift Codable</em> series</strong>, we’ll continue building on these fundamentals and explore more advanced decoding techniques, helping us move from understanding how Codable works on designing models that are easier to maintain, debug, and use in production.</p><p>The goal is simple: <strong>write decoding code that doesn’t just work with today’s API response, but is designed thoughtfully for the unexpected cases you’ll encounter tomorrow.</strong></p><p>If you found this article useful, follow along for the next part of the series.</p><p><strong>Happy coding!</strong> 🚀</p><p>#Swift #iOSDevelopment #SwiftCodable #JSON #MobileDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be15a1cb013c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift Codable]]></title>
            <link>https://medium.com/@khaledkamal/mastering-swift-codable-b0ce3b9d9aff?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ce3b9d9aff</guid>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 12:27:17 GMT</pubDate>
            <atom:updated>2026-10-15T12:27:17.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9Sz5cEF00IndyfWM1Q_1w.jpeg" /></figure><p><em>Understanding what really happens between an API response and your Swift model.</em></p><p>If you’re an iOS developer, you’ve probably written this line hundreds of times:</p><pre>let user = try JSONDecoder().decode(<br>    User.self,<br>    from: data<br>)</pre><p>It looks simple.</p><p>And most of the time, it is.</p><p>But have you ever stopped and asked:</p><p><strong>What actually happens when </strong><strong>decode() runs?</strong></p><p>How does Swift know that this JSON:</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><p>should become this:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>And what happens when the API doesn’t behave exactly as expected?</p><p>For example:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;<br>}</pre><p>When your model expects an Int.</p><p>Or:</p><pre>{<br>    &quot;name&quot;: null<br>}</pre><p>When your model expects a String.</p><p>Or perhaps the backend suddenly introduces a new enum value:</p><pre>{<br>    &quot;status&quot;: &quot;future_status&quot;<br>}</pre><p>These are the situations where simply knowing how to write JSONDecoder().decode() isn&#39;t enough.</p><p>You need to understand <strong>Codable itself</strong>.</p><h3>What Is Codable?</h3><p>Let’s start with the simplest definition.</p><pre>typealias Codable = Encodable &amp; Decodable</pre><p>In other words, Codable combines two protocols:</p><ul><li>Encodable</li><li>Decodable</li></ul><p>They represent two different directions of data transformation.</p><pre>External Data<br>     ↓<br> Decodable<br>     ↓<br>Swift Model</pre><p>And:</p><pre>Swift Model<br>     ↓<br> Encodable<br>     ↓<br>External Data</pre><p>For example:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>We can decode JSON into a User:</p><pre>let user = try JSONDecoder().decode(<br>    User.self,<br>    from: data<br>)</pre><p>And we can encode a User back into data:</p><pre>let data = try JSONEncoder().encode(user)</pre><p>That’s the basic idea behind Codable.</p><p>But there’s more to it.</p><h3>Codable Isn’t JSON</h3><p>This is one of the first things worth understanding.</p><p><strong>Codable Itself is not a JSON system.</strong></p><p>Codable defines a general mechanism for encoding and decoding Swift values.</p><p>JSONEncoder and JSONDecoder are implementations that use this mechanism to work with JSON.</p><p>Conceptually:</p><pre>Codable<br>              /     \<br>             /       \<br>      Encodable     Decodable<br>          ↓             ↓<br>       Encoder       Decoder<br>          ↓             ↓<br>     JSONEncoder   JSONDecoder</pre><p>This distinction becomes increasingly important when we start working with custom decoding and encoding.</p><h3>The Magic of Automatic Synthesis</h3><p>One of the reasons Codable is so convenient is that Swift can generate much of the implementation for us.</p><p>We can simply write:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>We don’t have to manually implement:</p><pre>init(from decoder: Decoder) throws</pre><p>or:</p><pre>func encode(to encoder: Encoder) throws</pre><p>Swift can synthesize these implementations automatically when the necessary conditions are satisfied.</p><p>That means a surprisingly small amount of code can hide quite a lot of behavior.</p><p>And understanding that behavior becomes important when automatic synthesis is no longer enough.</p><h3>What’s Happening Behind the Scenes?</h3><p>Consider our simple model again:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>Conceptually, the compiler generates decoding logic similar to:</p><pre>init(from decoder: Decoder) throws {<br>    let container = try decoder.container(<br>        keyedBy: CodingKeys.self<br>    )</pre><pre>    id = try container.decode(<br>        Int.self,<br>        forKey: .id<br>    )</pre><pre>    name = try container.decode(<br>        String.self,<br>        forKey: .name<br>    )<br>}</pre><p>And encoding logic similar to:</p><pre>func encode(to encoder: Encoder) throws {<br>    var container = encoder.container(<br>        keyedBy: CodingKeys.self<br>    )</pre><pre>    try container.encode(<br>        id,<br>        forKey: .id<br>    )</pre><pre>    try container.encode(<br>        name,<br>        forKey: .name<br>    )<br>}</pre><p>You normally don’t write this code.</p><p>Swift does it for you.</p><p>But this is the beginning of the mental model we will build throughout this series.</p><p>Eventually, we’ll need to understand things like:</p><ul><li>CodingKey</li><li>Decoder</li><li>Encoder</li><li>KeyedDecodingContainer</li><li>KeyedEncodingContainer</li><li>UnkeyedDecodingContainer</li><li>SingleValueDecodingContainer</li></ul><p>Once you understand these pieces, custom Codable becomes much easier to reason about.</p><h3>The Real World Is Messy</h3><p>Tutorial APIs are usually clean.</p><p>Real APIs aren’t always.</p><p>You might expect:</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;age&quot;: 30<br>}</pre><p>But receive:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;name&quot;: null,<br>    &quot;age&quot;: &quot;&quot;<br>}</pre><p>Or:</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;status&quot;: &quot;future_status&quot;<br>}</pre><p>Or even:</p><pre>{<br>    &quot;items&quot;: [<br>        {<br>            &quot;id&quot;: 1<br>        },<br>        null,<br>        {<br>            &quot;id&quot;: &quot;3&quot;<br>        }<br>    ]<br>}</pre><p>Now things become more interesting.</p><p>You need to think about:</p><ul><li>Missing keys</li><li>null</li><li>Empty strings</li><li>Empty arrays</li><li>Wrong types</li><li>Nested objects</li><li>Dynamic keys</li><li>Unknown enum values</li><li>Multiple possible types</li><li>Custom decoding</li><li>Custom encoding</li><li>Decoding errors</li><li>Lossy decoding</li><li>Default values</li><li>API evolution</li></ul><p>This is where understanding Codable becomes much more valuable than simply knowing the syntax.</p><h3>The Mental Model</h3><p>The goal of this series isn’t to teach you a collection of Codable tricks.</p><p>Instead, we’ll build a mental model that allows you to look at an API response and reason about it.</p><p>Imagine receiving something like:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;created_at&quot;: 1754656200000,<br>    &quot;status&quot;: &quot;future_status&quot;,<br>    &quot;profile&quot;: null,<br>    &quot;tags&quot;: [],<br>    &quot;metadata&quot;: {<br>        &quot;premium&quot;: true,<br>        &quot;score&quot;: &quot;98.5&quot;<br>    }<br>}</pre><p>Instead of immediately writing a Swift struct, we should start asking:</p><pre>What is the JSON structure?<br>        ↓<br>What Swift type represents it?<br>        ↓<br>Which keys are optional?<br>        ↓<br>Can values be null?<br>        ↓<br>Can the backend change types?<br>        ↓<br>Do I need CodingKeys?<br>        ↓<br>Do I need custom decoding?<br>        ↓<br>Should invalid data fail the entire object?<br>        ↓<br>Should this be a DTO or a domain model?</pre><p>That’s the mindset I want to develop throughout this series.</p><p>The goal isn’t simply:</p><blockquote><strong><em>“How do I decode this JSON?”</em></strong></blockquote><p>It’s:</p><blockquote><strong><em>“How do I design a reliable boundary between an external API and my Swift application?”</em></strong></blockquote><h3>What We’ll Cover</h3><p>This series will gradually move from the fundamentals to production-level Codable.</p><h3><a href="https://medium.com/@khaledkamal/part-1-fundamentals-swift-codable-beyond-jsondecoder-decode-b4e9aa66899e">Part 1 — Fundamentals</a></h3><p>We’ll start with:</p><ul><li>Codable</li><li>Encodable</li><li>Decodable</li><li>Automatic synthesis</li><li>CodingKey</li><li>Encoder</li><li>Decoder</li><li>Containers</li></ul><h3><a href="https://medium.com/@khaledkamal/part-2-practical-codable-swift-codable-beyond-jsondecoder-decode-be15a1cb013c">Part 2 — Practical Codable</a></h3><p>Then we’ll explore:</p><ul><li>Nested objects</li><li>Arrays</li><li>Dictionaries</li><li>Optionals</li><li>CodingKeys</li><li>Key strategies</li><li>Dates</li><li>Enums</li></ul><h3><a href="https://medium.com/@khaledkamal/part-3-edge-cases-dirty-apis-mastering-swift-codable-32a6fcd14b0b">Part 3 — Edge Cases</a></h3><p>Then we’ll deal with real-world API problems:</p><ul><li>Missing keys</li><li>null</li><li>Empty values</li><li>Wrong types</li><li>Inconsistent APIs</li><li>Unknown enum values</li><li>Partially corrupted arrays</li></ul><h3><a href="https://medium.com/@khaledkamal/part-4-custom-codable-mastering-swift-codable-4a66478a23fe">Part 4 — Custom Codable</a></h3><p>We’ll take control of the decoding and encoding process using:</p><pre>init(from decoder: Decoder) throws</pre><p>and:</p><pre>func encode(to encoder: Encoder) throws</pre><p>We’ll also dive deeper into keyed, unkeyed, and single-value containers.</p><h3>Part 5 — Advanced Codable</h3><p>We’ll explore:</p><ul><li>Property wrappers</li><li>Generics</li><li>Polymorphic JSON</li><li>Heterogeneous values</li><li>Lossy decoding</li><li>Flexible types</li></ul><h3>Part 6 — Production Codable</h3><p>Finally, we’ll connect Codable to real application architecture:</p><pre>Network<br>   ↓<br>Data<br>   ↓<br>JSONDecoder<br>   ↓<br>DTO<br>   ↓<br>Domain Model<br>   ↓<br>Application</pre><p>We’ll look at:</p><ul><li>Architecture</li><li>DTOs and domain models</li><li>Testing</li><li>Debugging</li><li>Performance</li><li>API evolution</li><li>Production trade-offs</li></ul><h3>The Goal</h3><p>By the end of this series, I don’t want you to simply know how to write:</p><pre>JSONDecoder().decode(...)</pre><p>I want you to be able to look at an unfamiliar API response and confidently answer:</p><blockquote><strong><em>How should I model this data, decode it safely, handle its edge cases, validate it, and prevent API problems from leaking into the rest of my application?</em></strong></blockquote><p>That’s the difference between <strong>using Codable</strong> and <strong>understanding Codable</strong>.</p><p>And that’s what we’re going to explore.</p><h3>Key Takeaways</h3><ul><li>Codable combines Encodable and Decodable.</li><li>Decodable represents the external-data → Swift direction.</li><li>Encodable represents the Swift → external-data direction.</li><li>JSONDecoder and JSONEncoder Use the Codable system to work with JSON.</li><li>Swift can automatically synthesize much of the Codable implementation.</li><li>Understanding synthesized Codable code makes custom decoding easier to understand.</li><li>Real-world APIs can contain missing values, null, inconsistent types, and unknown values.</li><li>Good Codable design is about creating a reliable boundary between your application and external data.</li></ul><h3>Odd / Interesting Things</h3><h3>1. Codable isn&#39;t actually JSON-specific</h3><p>Codable describes a general encoding and decoding mechanism.</p><p>JSON is just one representation supported through JSONEncoder and JSONDecoder.</p><h3>2. The compiler is doing more than you might think</h3><p>When you write:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>Swift can generate the encoding and decoding implementation for you.</p><h3>3. Property defaults don’t automatically solve decoding</h3><p>This:</p><pre>let name: String = &quot;&quot;</pre><p>doesn’t mean Codable will automatically use &quot;&quot; when the name key is missing.</p><p>We’ll explore exactly why in a future article.</p><h3>4. Many Codable problems are actually API-contract problems</h3><p>When decoding fails, the problem isn’t always your Swift code.</p><p>Sometimes the real issue is that the external system doesn’t provide a stable or predictable data contract.</p><p>Understanding Codable helps us design for that reality instead of pretending every API is perfect.</p><h3>What’s Next?</h3><p>Now that we’ve established <strong>why Codable deserves a deeper look</strong>, it’s time to understand what actually happens when we call:</p><pre>JSONDecoder().decode(...)</pre><p>In the next article: <a href="https://medium.com/@khaledkamal/part-1-fundamentals-swift-codable-beyond-jsondecoder-decode-b4e9aa66899e">https://medium.com/@khaledkamal/part-1-fundamentals-swift-codable-beyond-jsondecoder-decode-b4e9aa66899e</a></p><h3>Codable, Encodable &amp; Decodable — What Actually Happens When You Call decode()?</h3><p>We’ll follow the data step by step:</p><pre>JSON Data<br>    ↓<br>JSONDecoder<br>    ↓<br>Decoder<br>    ↓<br>CodingKeys<br>    ↓<br>Decoding Container<br>    ↓<br>Swift Values<br>    ↓<br>Swift Model</pre><p>That’s where we’ll start looking under the hood.</p><h3>Before We Begin</h3><p>Throughout this series, we’ll go beyond syntax and explore the reasoning behind Swift Codable.</p><p>We’ll examine how decoding works, why it fails, how to handle unpredictable API responses, and how to make better design decisions in real-world iOS applications.</p><p>My goal is to build a practical, step-by-step guide that helps iOS developers move from simply using Codable to understanding how it works under the hood.</p><p><strong>A question for you:</strong></p><p>What is the most challenging Codable problem you’ve faced in a real project?</p><p>Was it inconsistent API responses, custom decoding, unexpected null values, unknown enum cases, or something else?</p><p>Share your experience in the comments. Your real-world challenges could inspire future articles in this series.</p><p>If you’re ready to understand Codable beyond, let&#39;s start with the fundamentals.</p><p><strong>Next up: </strong><a href="https://medium.com/@khaledkamal/part-1-fundamentals-mastering-swift-codable-b4e9aa66899e"><strong>Part 1</strong></a><strong> — Codable, Encodable &amp; Decodable: What Actually Happens When You Call </strong><strong>decode()?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ce3b9d9aff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1 — Fundamentals: Mastering Swift Codable]]></title>
            <link>https://medium.com/@khaledkamal/part-1-fundamentals-mastering-swift-codable-b4e9aa66899e?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e9aa66899e</guid>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 12:27:14 GMT</pubDate>
            <atom:updated>2026-10-15T12:27:14.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9Sz5cEF00IndyfWM1Q_1w.jpeg" /></figure><p>Understanding what really happens between an API response and your Swift model.</p><h3>1. What is Codable?</h3><p>Codable is a protocol composition:</p><pre>typealias Codable = Encodable &amp; Decodable</pre><p>So:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>means:</p><pre>struct User: Encodable, Decodable {<br>    let id: Int<br>    let name: String<br>}</pre><p>There are two directions:</p><pre>Swift Object<br>    │<br>    │ Encodable<br>    ▼<br>Encoder<br>    │<br>    ▼<br>JSON / Property List / other format</pre><p>and:</p><pre>JSON / Property List / other format<br>    │<br>    ▼<br>Decoder<br>    │<br>    ▼<br>Swift Object<br>    ▲<br>    │ Decodable</pre><p>The important point:</p><blockquote><strong><em>Codable itself doesn’t mean JSON.</em></strong></blockquote><p>Codable describes how a Swift type can be transformed to/from an external representation.</p><p>JSONEncoder and JSONDecoder are implementations for JSON.</p><h3>2. Encodable vs Decodable</h3><h3>Encodable</h3><p>Means:</p><blockquote><em>“This Swift value knows how to represent itself to an encoder.”</em></blockquote><p>Conceptually:</p><pre>protocol Encodable {<br>    func encode(to encoder: Encoder) throws<br>}</pre><p>For example:</p><pre>struct User: Encodable {<br>    let id: Int<br>    let name: String<br>}</pre><p>You can do:</p><pre>let encoder = JSONEncoder()</pre><pre>let data = try encoder.encode(user)</pre><h3>Decodable</h3><p>Means:</p><blockquote><em>“This Swift type knows how to construct itself from a decoder.”</em></blockquote><p>Conceptually:</p><pre>protocol Decodable {<br>    init(from decoder: Decoder) throws<br>}</pre><p>So:</p><pre>let decoder = JSONDecoder()</pre><pre>let user = try decoder.decode(User.self, from: data)</pre><p>Notice the difference:</p><pre>Encodable<br>    value → encoder</pre><pre>Decodable<br>    decoder → value</pre><h3>3. What does the compiler actually generate?</h3><p>Consider:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>You didn’t write:</p><pre>init(from decoder: Decoder)</pre><p>or:</p><pre>func encode(to encoder: Encoder)</pre><p>Yet it works.</p><p>Why?</p><p>Because Swift can <strong>synthesize</strong> the implementation for you.</p><p>Conceptually, imagine the compiler generated something similar to:</p><pre>extension User {<br>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        self.id = try container.decode(<br>            Int.self,<br>            forKey: .id<br>        )</pre><pre>        self.name = try container.decode(<br>            String.self,<br>            forKey: .name<br>        )<br>    }</pre><pre>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(<br>            keyedBy: CodingKeys.self<br>        )</pre><pre>        try container.encode(id, forKey: .id)<br>        try container.encode(name, forKey: .name)<br>    }<br>}</pre><p>And conceptually:</p><pre>enum CodingKeys: String, CodingKey {<br>    case id<br>    case name<br>}</pre><p>You normally don’t see these generated implementations.</p><p>That’s <strong>synthesis</strong>.</p><h3>4. Why does synthesis work?</h3><p>Swift can synthesize Codable When it can determine a straightforward mapping between your properties and their encoded representation.</p><p>For example:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>has:</p><pre>Swift property       JSON key<br>──────────────────────────────<br>id                    &quot;id&quot;<br>name                  &quot;name&quot;</pre><p>Very predictable.</p><p>It becomes more interesting when you have:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    let address: Address<br>}</pre><p>If:</p><pre>struct Address: Codable {<br>    let city: String<br>}</pre><p>Then Swift can recursively synthesize the decoding:</p><pre>User<br> │<br> ├── id → Int<br> │<br> ├── name → String<br> │<br> └── address → Address<br>                  │<br>                  └── city → String</pre><p>Because Address itself is Decodable.</p><h3>5. The most important mental model</h3><p>Don’t think:</p><blockquote><em>“JSONDecoder magically creates my object.”</em></blockquote><p>Think:</p><pre>JSONDecoder<br>     │<br>     ▼<br>   Decoder<br>     │<br>     ▼<br>  Containers<br>     │<br>     ▼<br>  Individual values<br>     │<br>     ▼<br> Swift properties</pre><p>For:</p><pre>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;John&quot;<br>}</pre><p>Swift conceptually sees:</p><pre>JSON object<br>     │<br>     ▼<br>Keyed container<br>     │<br>     ├── &quot;id&quot;   → Int<br>     │<br>     └── &quot;name&quot; → String</pre><p>This is why understanding <strong>containers</strong> is the key to mastering Codable.</p><h3>6. The Codable ecosystem</h3><p>Here is the architecture you should memorize:</p><pre>Codable<br>                  /         \<br>                 /           \<br>          Encodable          Decodable<br>              │                  │<br>              ▼                  ▼<br>           Encoder            Decoder<br>              │                  │<br>              ▼                  ▼<br>       EncodingContainer   DecodingContainer<br>              │                  │<br>       ┌──────┼──────┐    ┌──────┼──────┐<br>       ▼      ▼      ▼    ▼      ▼      ▼<br>    Keyed   Unkeyed Single  Keyed Unkeyed Single</pre><p>There are <strong>three fundamental </strong>representations.</p><h3>Keyed</h3><p>For JSON objects:</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><p>Uses:</p><pre>KeyedDecodingContainer<br>KeyedEncodingContainer</pre><h3>Unkeyed</h3><p>For arrays:</p><pre>[<br>    1,<br>    2,<br>    3<br>]</pre><p>Uses:</p><pre>UnkeyedDecodingContainer<br>UnkeyedEncodingContainer</pre><h3>Single value</h3><p>For a single JSON value:</p><pre>123</pre><p>or:</p><pre>&quot;John&quot;</pre><p>or:</p><pre>true</pre><p>Uses:</p><pre>SingleValueDecodingContainer<br>SingleValueEncodingContainer</pre><p>This distinction becomes <strong>extremely important</strong> when we start implementing custom Codable.</p><h3>7. CodingKey</h3><p>CodingKey represents a key in a keyed container.</p><p>For example:</p><pre>{<br>    &quot;user_id&quot;: 123,<br>    &quot;user_name&quot;: &quot;John&quot;<br>}</pre><p>You could define:</p><pre>enum CodingKeys: String, CodingKey {<br>    case userID = &quot;user_id&quot;<br>    case userName = &quot;user_name&quot;<br>}</pre><p>Now:</p><pre>container.decode(Int.self, forKey: .userID)</pre><p>means:</p><pre>CodingKeys.userID<br>       │<br>       ▼<br>   &quot;user_id&quot;<br>       │<br>       ▼<br>      123</pre><p>So CodingKey is essentially the bridge between your Swift representation and the external key representation.</p><h3>8. What exactly is a KeyedDecodingContainer?</h3><p>Suppose:</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><p>The decoder can give you a keyed container:</p><pre>let container = try decoder.container(<br>    keyedBy: CodingKeys.self<br>)</pre><p>You can then ask:</p><pre>let id = try container.decode(<br>    Int.self,<br>    forKey: .id<br>)</pre><p>and:</p><pre>let name = try container.decode(<br>    String.self,<br>    forKey: .name<br>)</pre><p>Think of it as:</p><pre>KeyedDecodingContainer</pre><pre>       JSON object<br>           │<br>     ┌─────┴─────┐<br>     ▼           ▼<br>   &quot;id&quot;        &quot;name&quot;<br>     │           │<br>     ▼           ▼<br>    Int        String</pre><h3>9. Why are there different containers?</h3><p>Because JSON has different structural shapes.</p><h3>Object</h3><pre>{<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;age&quot;: 25<br>}</pre><p>→ keyed container.</p><h3>Array</h3><pre>[<br>    &quot;John&quot;,<br>    &quot;Mike&quot;<br>]</pre><p>→ unkeyed container.</p><h3>Single value</h3><pre>&quot;John&quot;</pre><p>→ single-value container.</p><p>This gives us a powerful mental model:</p><blockquote><strong><em>Before decoding a value, Codable needs to understand the shape of the encoded data.</em></strong></blockquote><h3>10. What happens here?</h3><p>Now let’s examine:</p><pre>let user = try JSONDecoder().decode(<br>    User.self,<br>    from: data<br>)</pre><p>At a high level:</p><pre>Data<br>                  │<br>                  ▼<br>             JSONDecoder<br>                  │<br>                  ▼<br>              Decoder<br>                  │<br>                  ▼<br>          User.init(from:)<br>                  │<br>                  ▼<br>      decoder.container(keyedBy:)<br>                  │<br>                  ▼<br>       KeyedDecodingContainer<br>             /          \<br>            /            \<br>           ▼              ▼<br>     decode(Int)      decode(String)<br>           │              │<br>           ▼              ▼<br>          123           &quot;John&quot;<br>           │              │<br>           └──────┬───────┘<br>                  ▼<br>             User(...)</pre><p>Later, we’ll go much deeper into what is happening inside the decoder and what is and isn’t guaranteed by the Decoderabstraction.</p><h3>11. When does synthesis fail?</h3><p>This is an important interview topic.</p><p>Synthesis can stop being sufficient when your Swift representation doesn’t directly correspond to the encoded representation.</p><p>For example, suppose the server gives:</p><pre>{<br>    &quot;id&quot;: &quot;123&quot;<br>}</pre><p>But you want:</p><pre>struct User: Codable {<br>    let id: Int<br>}</pre><p>The default decoder expects an Int.</p><p>It does <strong>not</strong> automatically decide:</p><pre>&quot;123&quot; → 123</pre><p>You need custom decoding or a custom type.</p><p>Another example:</p><pre>{<br>    &quot;type&quot;: &quot;image&quot;,<br>    &quot;url&quot;: &quot;...&quot;,<br>    &quot;width&quot;: 100<br>}</pre><p>where the Swift type depends on &quot;type&quot;.</p><p>Now you need logic:</p><pre>type == image<br>      ↓<br>Image</pre><p>rather than simply:</p><pre>JSON key → Swift property</pre><p>That’s where custom init(from:) becomes important.</p><h3>12. One subtle but critical point</h3><p>A property being declared with a default value:</p><pre>struct User: Codable {<br>    let name: String = &quot;&quot;<br>}</pre><p>does <strong>not</strong> mean:</p><blockquote><em>“If JSON doesn’t contain </em><em>name, use </em><em>&quot;&quot;.&quot;</em></blockquote><p>This is one of the most common Codable misconceptions.</p><p>We’ll prove exactly why later when we study, synthesize, and property initialization.</p><h3>Your first exercise</h3><p>Don’t look for the solution yet. I want you to reason about the Codable system.</p><p>Consider:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>}</pre><p>and:</p><pre>{<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><h3>Question 1</h3><p>When this runs:</p><pre>let user = try JSONDecoder().decode(<br>    User.self,<br>    from: data<br>)</pre><p>Walk me through what you think happens <strong>step by step</strong>.</p><p>Try to answer these:</p><ol><li>What does JSONDecoder receive?</li><li>What does User.self it tell the decoder?</li><li>Who calls User.init(from:)?</li><li>Where does CodingKeys it come into play?</li><li>Why does decoding an object require a <strong>keyed container</strong>?</li><li>What happens when this is executed conceptually?</li></ol><pre>container.decode(Int.self, forKey: .id)</pre><ol><li>What happens if &quot;id&quot; Doesn&#39;t exist?</li><li>What happens if &quot;id&quot; exists but contains:</li></ol><pre>&quot;id&quot;: &quot;123&quot;</pre><p>instead of:</p><pre>&quot;id&quot;: 123</pre><h3>Question 2 — Container thinking</h3><p>Classify each JSON value by the container you expect to use:</p><pre>{<br>    &quot;name&quot;: &quot;John&quot;<br>}</pre><pre>[1, 2, 3]</pre><pre>&quot;John&quot;</pre><pre>123</pre><pre>true</pre><pre>{<br>    &quot;items&quot;: [1, 2, 3]<br>}</pre><h3>Final Thoughts</h3><p>Codable It can look deceptively simple.</p><p>You write:</p><pre>let user = try JSONDecoder().decode(<br>    User.self,<br>    from: data<br>)</pre><p>and somehow JSON becomes a Swift object.</p><p>But there isn’t really any magic.</p><p>Underneath, Swift is working with protocols, synthesized implementations, coding keys, decoders, and containers to transform one representation into another.</p><p>The most important thing at this stage isn’t memorizing every API.</p><p>It’s building the right mental model:</p><pre>External Data<br>     ↓<br>   Decoder<br>     ↓<br>   Container<br>     ↓<br>   Values<br>     ↓<br> Swift Model</pre><p>Once you understand that flow, things like CodingKeys, nested containers, custom decoding, DecodingError, and even complicated API responses become much easier to reason about.</p><p>And this is just the beginning.</p><p>In the next article, we’ll go one level deeper and answer a question that is easy to overlook:</p><blockquote><strong><em>What actually happens when you call </em></strong><strong><em>JSONDecoder().decode()?</em></strong></blockquote><p>We’ll follow the decoding process step by step and see where Decoder, init(from:), CodingKeys, and containers fit into the picture.</p><h3>Key Takeaways</h3><ul><li>Codable combines Encodable and Decodable.</li><li>Codable is not limited to JSON.</li><li>JSONEncoder and JSONDecoder handle JSON representations.</li><li>Swift can automatically synthesize much of your Codable implementation.</li><li>CodingKey connects Swift properties with encoded keys.</li><li>JSON objects use <strong>keyed containers</strong>.</li><li>JSON arrays use <strong>unkeyed containers</strong>.</li><li>Single JSON values use <strong>single-value containers</strong>.</li><li>Containers can be nested.</li><li>Automatic synthesis works best when the Swift model matches the external data.</li><li>Understanding the <strong>decoding mental model</strong> is more valuable than memorizing Codable tricks.</li></ul><h3>Odd / Interesting Things</h3><blockquote><strong><em>Codable doesn’t actually decode JSON.</em></strong></blockquote><p>Decodable describes how a Swift type can be created from an external representation. JSON is just one format that can provide that representation.</p><blockquote><strong><em>The compiler writes Codable code for you.</em></strong></blockquote><p>When synthesis is possible, you don’t have to manually write init(from:) or encode(to:).</p><blockquote><strong><em>A default property value doesn’t automatically handle a missing JSON key.</em></strong></blockquote><p>This is one of the easiest Codable behaviors to misunderstand — and we’ll explore exactly why in a later article.</p><h3>Coming Next</h3><p><strong>Article 2 — Codable, Encodable &amp; Decodable: What Actually Happens When You Call </strong><strong>decode()?</strong></p><p>We’ll take this:</p><pre>JSONDecoder().decode(User.self, from: data)</pre><p>and follow it from:</p><pre>Data<br> ↓<br>JSONDecoder<br> ↓<br>Decoder<br> ↓<br>User.init(from:)<br> ↓<br>CodingKeys<br> ↓<br>KeyedDecodingContainer<br> ↓<br>Swift Properties</pre><p><strong>That’s where Codable starts getting really interesting.</strong></p><h3>Before Moving to Part 2</h3><p>You’ve now built the foundation for understanding Swift Codable—from protocol composition and compiler synthesis to coding keys, decoding containers, and the overall decoding flow.</p><p>The next step is to move beyond knowing what these components are and understand how they work together.</p><p>Before continuing, take a few minutes to answer the exercises in this article. Try to explain the decoding process in your own words, especially what happens when you call JSONDecoder().decode(User.self, from: data).</p><p>You don’t need to know every implementation detail yet. What matters is developing a mental model that helps you reason about the behavior instead of relying on trial and error.</p><p><strong>Your turn:</strong> Have you ever struggled with a Codable issue that seemed mysterious at first? Share your experience or your answers to the exercises in the comments. Your question might help someone else facing the same problem.</p><p>In <a href="https://medium.com/@khaledkamal/part-2-practical-codable-mastering-swift-codable-be15a1cb013c">Part 2</a>, we’ll go deeper into the decoding process and examine what actually happens when you call decode()—step by step.</p><p>Because once you understand what happens behind the scenes, Codable stops feeling like magic and becomes a system you can reason about, debug, and customize with confidence.</p><p><strong>See you in </strong><a href="https://medium.com/@khaledkamal/part-2-practical-codable-mastering-swift-codable-be15a1cb013c"><strong>Part 2</strong></a><strong>. Happy coding!</strong></p><p>#Swift #iOSDevelopment #SwiftCodable #JSON #MobileDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e9aa66899e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IOS Concurrency]]></title>
            <link>https://medium.com/@khaledkamal/ios-concurrency-ddb4d148b753?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb4d148b753</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Mon, 29 Jul 2019 11:36:04 GMT</pubDate>
            <atom:updated>2019-07-29T11:36:04.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aWsObdIOAB0mYjdjkhhbOQ.jpeg" /></figure><h3>Concurrency</h3><p>In <a href="https://en.wikipedia.org/wiki/Computer_science">computer science</a>, <strong>concurrency</strong> is the ability of different parts or units of a program, algorithm, or problem to be executed out-of-order or in partial order, without affecting the final outcome. I do not understand 😞 , Let’s explain .<br>Moderns devices almost have more than a single CPU “<a href="https://en.wikipedia.org/wiki/Multi-core_processor">Multi-core processor</a>”,<br>Having more than one core means they are capable of running more than a single task at the same time. By splitting your app into logical “chunks” of code you enable the iOS device to run multiple parts of your program at the same time, thus improving overall performance.</p><h3>Parallelism</h3><p>Parallelism means performing two or more tasks simultaneously. Parallel computing in computer science refers to the process of performing multiple calculations simultaneously.<br><em>Parallelism doesn’t require two tasks to exist. It physically runs parts of tasks or multiple tasks, at the same time using the multi-core infrastructure of CPU.</em></p><h4>Concurrency vs Parallelism</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*ajL00xgRJO2HzWEIQMxXXA.png" /></figure><p><strong>Parallelism:</strong> is about doing work at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAP-UydEhpGbiOgU6VxIiA.jpeg" /></figure><p><strong>Concurrency:</strong> is about the option to do work at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDqlZ9NrRVsM8Qf9vI2Y2g.jpeg" /></figure><h4>How is concurrency related to parallelism?</h4><ul><li>Concurrency and Parallelism refer to computer architectures which focus on how our tasks or computations are performed.</li><li><strong><em>In a single core environment, concurrency happens</em></strong> with tasks executing over same time period via <a href="https://en.wikipedia.org/wiki/Context_switch">Context switching</a> i.e at a particular time period, only a single task gets executed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*V_dl0A6Hy8LM_jr4T7Bv5w.png" /></figure><ul><li><strong><em>In a multi-core environment, concurrency can be achieved via parallelism </em></strong>in which multiple tasks are executed simultaneously.</li></ul><p><a href="https://softwareengineering.stackexchange.com/questions/190719/the-difference-between-concurrent-and-parallel-execution">More Explantation</a></p><h3><strong>Common terminology</strong></h3><ul><li><strong>Process,</strong> An instance of an executing app , this includes your stack, heap, and all other resources.</li><li><strong>Thread,</strong> Path of execution for code.</li><li><strong>Multithreading,</strong> Multiple threads or multiple paths of execution running at the same time.</li></ul><h3>Threads</h3><p>is the smallest sequence of programmed instructions that can be managed independently by a <a href="https://en.wikipedia.org/wiki/Scheduling_(computing)">scheduler</a>, which is typically a part of the <a href="https://en.wikipedia.org/wiki/Operating_system">operating system</a>.</p><p>You can subclass Thread and override the <a href="https://developer.apple.com/documentation/foundation/thread/1418421-main">main()</a> method to implement your thread’s main entry point. If you override <a href="https://developer.apple.com/documentation/foundation/thread/1418421-main">main()</a>, you do not need to invoke the inherited behavior by calling super.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/527e8250f295c573c87dd40e087d0a2b/href">https://medium.com/media/527e8250f295c573c87dd40e087d0a2b/href</a></iframe><p>But since iOS 10 and macOS Sierra, it’s finally possible on all platforms to just create a new thread using the initializer that allows to specify the closure that the thread will execute</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2a0391f9d9539e253b22bdaada618c6/href">https://medium.com/media/f2a0391f9d9539e253b22bdaada618c6/href</a></iframe><blockquote><em>It’s limited to 64 threads at the same time for one process.</em></blockquote><blockquote>You can use these semantics to cancel the execution of a thread or determine if the thread is still executing or has finished its task. Canceling a thread requires support from your thread code; see the description for <a href="https://developer.apple.com/documentation/foundation/thread/1411303-cancel">cancel()</a> for more information.</blockquote><p><a href="https://developer.apple.com/documentation/foundation/thread">For More Information .</a></p><h3>Grand Central Dispatch “GCD” :</h3><p>There are two APIs that you’ll use when making your app concurrent: Grand Central Dispatch, commonly referred to as <strong>GCD</strong>, and <strong>Operations</strong>.</p><p>The Grand Central Dispatch (<strong>GCD</strong>) is a queue based API that allows to execute closures on workers pools.<br>In other words, closures containing a job that need to be executed can be added to a queue that will execute them using a series of threads either sequentially or in parallel depending on the queue’s configuration options , But regardless of the type of queue</p><blockquote>Note : All of the tasks that GCD manages for you are placed into GCD-managed first-in, first-out (FIFO) queues.</blockquote><h3>Synchronous VS Asynchronous</h3><p>Before we explain more on “ <strong>GCD</strong>” , We should learn about (Synchronous and Asynchronous)<br>Work placed into the queue may either run:<br><strong> Synchronous</strong> : your app will wait and block the current run loop until execution finishes before moving on to the next task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*eT8vZCzcbGrZc4tGxY_Reg.png" /></figure><p><strong>Asynchronous</strong> : will start, but return execution to your app immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*8uKHi6zDqAjv6GHseLYv-w.png" /></figure><h3>Serial and concurrent queues</h3><p>We explained before that the Grand Central Dispatch (<strong>GCD</strong>) is a <strong>queue</strong> based API.The queue to which your task is submitted also has a characteristic of being either <strong>serial</strong> or <strong>concurrent.<br>Serial</strong> queues only have a single thread associated.<br><strong>Concurrent</strong> queue, on the other hand, is able to utilize as many threads as the system has resources for.</p><blockquote>Note: Threads will be created and released as necessary on a concurrent queue.</blockquote><p>I have question , Does asynchronous mean concurrent ? <br>Being synchronous or asynchronous simply identifies whether or not the queue on which you’re running the task must wait for the task to complete before it can spawn the next task.</p><p><strong>Serial</strong><br>Synchronous (one thread ) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*3tJkE-LIkUoXFcza4f3L3Q.png" /></figure><p>Asynchronous (one thread ) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*tXo2W5ENs8oVMzbIE-ycFw.png" /></figure><p><strong>Concurrent</strong><br>Synchronous (multi-threaded) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*u6yPC6Oizg2zqWUN1u9Uvw.png" /></figure><p>Asynchronous (multi-threaded) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*VaVDYLj5IgCHvSG9SEEqHw.png" /></figure><h3>Dispatch queues :</h3><p>The way you work with threads is by creating a queue , To create queue in Swift by using “<strong>Dispatch queues</strong>”, Creating a dispatch queue is pretty simple on your part, as you can see in the example below:</p><pre>//serial Queue<br>let slabel = &quot;com.YourCompanyName.YourAppName.Identifier&quot;<br>let queue = DispatchQueue(label: slabel)</pre><pre>//concurretn Queue<br>let clabel = &quot;com.YourCompanyName.YourAppName.Identifier&quot;<br>let queue = DispatchQueue(label:clabel , attributes: .concurrent)</pre><p>To create a basic serial queue, a queue that will execute your closures sequentially, you just need to provide a string label that will identify it.</p><p>The second queue we created is concurrent, meaning that the queue will use all the available threads in its underlying thread pool when executing the jobs it contains.</p><p>Apple has made two Dispatch queues for you , one is serial “The main queue” , other is concurrent “The global queue<strong>”.</strong></p><p><strong>The main queue:<br></strong>When your app starts, a main dispatch queue is automatically created for you. It’s a serial queue that’s responsible for your UI</p><pre>DispatchQueue.main.async {<br>cell.imageView = self.images[index.item]<br>}</pre><blockquote>Note:You never want to execute something synchronously against the main queue<br>unless it’s related to actual UI work.</blockquote><p><strong>The global queue:<br></strong>Concurrent queues theat depending on the Quality of service (<strong>QoS</strong>).</p><pre>let queue = DispatchQueue.global(qos: <strong>DispatchQoS</strong>)</pre><p><strong>Quality of service “DispatchQoS”:<br></strong>When using a concurrent dispatch queue, you’ll need to tell iOS how important the tasks are that get sent to the queue so that it can properly prioritize the work that needs to be done against all the other tasks that are clamoring for resources . Apple offers six quality of service classes.<br>The different levels of priority are declared in the DispatchQoS class, from higher to lower:</p><ul><li>.<strong>userInteractive</strong> : tasks, such as animations, event handling, or updating your app’s user interface.</li><li>.<strong>userInitiated</strong> : tasks that prevent the user from actively using your app , Tasks performed in this queue should take a few seconds or less to complete.</li><li>.<strong>default</strong> :The default quality-of-service class , The priority level of this QoS falls between user-initiated and utility. This QoS is not intended to be used by developers to classify work.</li><li>.<strong>utility</strong> : “ tasks that would typically include a progress indicator such as long-running computations, I/O, networking or continuous data feeds”</li><li>.<strong>background</strong> : maintenance or cleanup tasks that you create</li><li>.<strong>unspecified</strong> :The absence of a quality-of-service class</li></ul><p>What is the difference between main queue and queue with QOS as <strong>userInteractive? </strong><a href="https://stackoverflow.com/questions/45912528/is-dispatchqueue-globalqos-userinteractive-async-same-as-dispatchqueue-main/45912978"><strong>Here</strong></a></p><p>Wait me for second part , and Thank you ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb4d148b753" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift SOLID Principles]]></title>
            <link>https://medium.com/@khaledkamal/swift-solid-principles-9f3fce777656?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f3fce777656</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 12:13:52 GMT</pubDate>
            <atom:updated>2019-06-19T12:13:52.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7jsOI-Asz42AsYXVCTrFA.jpeg" /></figure><p><strong>SOLID </strong>is an acronym for 5 important design principles when doing <strong>OOP</strong> (Object Oriented Programming) ,Or <strong>POP</strong> (Protocol oriented Programming).</p><p>These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend. They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.</p><h3>S.O.L.I.D stands for:</h3><p>When expanded the acronyms might seem complicated, but they are pretty simple to grasp.</p><ul><li><strong>S </strong>→ Single-responsiblity principle</li><li><strong>O </strong>→ Open-closed principle</li><li><strong>L</strong> → Liskov substitution principle</li><li><strong>I</strong> → Interface segregation principle</li><li><strong>D</strong> → Dependency Inversion Principle</li></ul><p>Let’s look at each principle individually to understand why S.O.L.I.D can help make us better developers.</p><h3><strong>1- Single-responsiblity principle (SRP).</strong></h3><p>There should never be more than one reason for a class to change. <strong>What is the meaning</strong> 🤔?<br>A class should have only a single responsibility (i.e. changes to only one part of the software’s specification should be able to affect the specification of the class).</p><p>Let’s build Messanger API , that includes receive message and send message .<br><strong>Wrong way .</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29690a682e9bd7763a84d752b53e3628/href">https://medium.com/media/29690a682e9bd7763a84d752b53e3628/href</a></iframe><p><strong>After implementing “Single responsibility “</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfcf2fbbeaf849e8f32ace15a2c9bfaa/href">https://medium.com/media/bfcf2fbbeaf849e8f32ace15a2c9bfaa/href</a></iframe><p><a href="https://gist.github.com/5ldkamal/f019408e2a4ddc85114eab1570004429"><strong>Exmaple2</strong></a><strong><br></strong><a href="https://gist.github.com/5ldkamal/7f458708ed5bdc61fadb8ecce6f57e8d"><strong>Exmaple3</strong></a><strong><br>Why should we use SP?</strong> Because it adds a lot of manageability problems for you in the long run.</p><h3>2- The Open-Closed Principle (OCP) “Abstraction”</h3><p>Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. <strong>What is the meaning</strong> 🤔?<br>If you want to create a class easy to maintain, it must have two important characteristics:</p><ul><li><strong>Open for extension</strong>: You should be able to extend or change the behaviours of a class without efforts.</li><li><strong>Closed for modification</strong>: You must extend a class without changing the implementation.</li></ul><p><strong>Wrong way .</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1ab037e9591fe5d89889b03a2facbc/href">https://medium.com/media/5f1ab037e9591fe5d89889b03a2facbc/href</a></iframe><p>If we wanna add new <strong>shape</strong> , we should change “ <strong>draw function implementation” etc.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*1rVb86dt4cRgUuhnqpeGeQ.png" /></figure><p>draw function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*HaL2AskBR2x8vLgUE-CaOQ.png" /></figure><p>and this is wrong , our class should be closed for modification.</p><p><strong>After implementing “OCP”</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a39a82708fb3cf57bdf885716dd51f9/href">https://medium.com/media/1a39a82708fb3cf57bdf885716dd51f9/href</a></iframe><p><a href="https://gist.github.com/5ldkamal/0ac3413af2b2b28b335d9271769a73c5"><strong>Exmaple2</strong></a></p><p><strong>Why should we use OCP ?</strong>The general idea of this principle is great. It tells you to write your code so that you will be able to add new functionality without changing the existing code. That prevents situations in which a change to one of your classes also requires you to adapt all depending classes.</p><h3>3-The Liskov Substitution Principle (LSP)“Decorator”</h3><p>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.<strong>What is the meaning</strong> 🤔?<br><em>“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”</em></p><p>The four conditions for abiding by the Liskov Substitution principle are as follows:<br><strong>* Method signatures must match</strong><br> Methods must take the same parameters</p><p><strong><em>* The preconditions for any method can’t be greater than that of its parent</em></strong><br> Any inherited method should not have more conditionals that change the return of that method, such as throwing an Exception</p><p><strong>* Post conditions must be at least equal to that of its parent</strong><br>Inherited methods should return the same type as that of its parent</p><p><strong>* Exception types must match<br></strong>If a method is designed to return a Exceptionin the event of an error, the same condition in the inherited method must return a Exception too</p><p>example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d56c9a4cd2acaeb607109df0d70bc8b4/href">https://medium.com/media/d56c9a4cd2acaeb607109df0d70bc8b4/href</a></iframe><p><strong>Why should we use LSP ?</strong>Code that adheres to LSP is loosely dependent to each other and encourages code reusability.</p><h3>4- Interface Segregation Principle (ISP)</h3><p><em>Clients should not be forced to depend upon interfaces that they don’t use.<br></em><strong>Wrong way .</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5cf3a6473087feb67946228d37df237/href">https://medium.com/media/b5cf3a6473087feb67946228d37df237/href</a></iframe><p><strong>After implementing “Interface Principle”</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/125f0463d84bbe0d86c13d8efa983017/href">https://medium.com/media/125f0463d84bbe0d86c13d8efa983017/href</a></iframe><p><a href="https://gist.github.com/5ldkamal/e3510219ec7f7584ad2949c68855eebb"><strong>Exmaple2</strong></a></p><p><strong>Why should we use ISP ?</strong>The Interface Segregation principle ensures that Interfaces are developed so that each of them have their own responsibility and thus they are specific, easily understandable, and re-usable.</p><h3>5- Dependency Inversion Principle (DIP)</h3><p><strong><em>A</em></strong><em>. High-level modules should not depend on low-level modules. Both should depend on </em><a href="https://en.wikipedia.org/wiki/Abstraction_(computer_science)"><em>abstractions</em></a><em>.<br></em><strong><em>B</em></strong><em>. Abstractions should not depend on details. Details should depend on abstractions.</em></p><h4><strong>Wrong way .</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ddfbef1e7e58e412cdc03a747528154/href">https://medium.com/media/0ddfbef1e7e58e412cdc03a747528154/href</a></iframe><p><strong>After implementing “DI”</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17d4780071890ac9b20b811c21b7b8de/href">https://medium.com/media/17d4780071890ac9b20b811c21b7b8de/href</a></iframe><h3><a href="https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#toc-conclusion">Conclusion</a></h3><p>Honestly, <strong>S.O.L.I.D</strong> might seem to be a handful at first, but with continuous usage and adherence to its guidelines, it becomes a part of you and your code which can easily be extended, modified, tested, and refactored without any problems.<br>By applying these 5 principles that make the <strong>SOLID </strong>acronym, we get to benefit from a reusable, maintainable, scalable and easy testable codebase.<br>These are 5 essential principles used by professional software engineers all around the globe, and if you are serious about creating ‘solid’ software, you should start applying these principles today!</p><p>To learn about <strong>GOF </strong><a href="https://medium.com/@khaledkamal/diving-in-design-pattern-swift-2a1c5861495c">Part1</a> , <a href="https://medium.com/@khaledkamal/diving-in-design-pattern-swift-part-2-f89603d3032d">Part2</a> , Thank you ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f3fce777656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving in Design Pattern Swift Part 2]]></title>
            <link>https://medium.com/@khaledkamal/diving-in-design-pattern-swift-part-2-f89603d3032d?source=rss-5a916709b0c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89603d3032d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[khaled kamal]]></dc:creator>
            <pubDate>Wed, 17 Apr 2019 20:31:03 GMT</pubDate>
            <atom:updated>2019-04-17T20:31:03.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5VWDFideHVENOPPJe-m4sg.jpeg" /></figure><p>Hello to Part2 , Check out <a href="https://medium.com/@khaledkamal/diving-in-design-pattern-swift-2a1c5861495c"><strong>Part1</strong></a> if you haven’t already :). Let’s get started.</p><h3>Structural Pattern</h3><p>Structural design patterns aim to simplify the design by finding an easy way of realizing <strong>relationships</strong> between <strong>classes</strong> and <strong>objects</strong>.</p><h4>1- Adapter Pattern :</h4><p>allows objects with incompatible interfaces to work together.The Adapter design pattern converts the interface of a class into another interface that clients expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*VvzMRSbS_nNaah-4ikaIzA.png" /></figure><blockquote>1- The<strong> new protocol</strong> is the desired protocol for use , sometimes called <strong>Target</strong>.<br>2- An <strong>adapter</strong> is created to conform to the protocol.<br>3- An <strong>object</strong> using an adapter , sometimes called <strong>Adaptee</strong>.</blockquote><p>Example : 1 <br>we have an O<strong>ld</strong> Api , we need to convert it to expected new interface that return <strong>UserData</strong> and <strong>Token.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de3409f3845434e1b890ecfa7dbe1e93/href">https://medium.com/media/de3409f3845434e1b890ecfa7dbe1e93/href</a></iframe><p>//Target :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c1f122ac2b11fc5f9d6855606a69362/href">https://medium.com/media/3c1f122ac2b11fc5f9d6855606a69362/href</a></iframe><p>//Adapter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd9f3add48029fdc32a194550e43d5b/href">https://medium.com/media/3cd9f3add48029fdc32a194550e43d5b/href</a></iframe><p>//Adaptee :- using Adapter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukdGtWqGf0A_98oi1h240Q.png" /></figure><p><strong>What should you be careful about?<br></strong>Protocols are a requirement for the adapter design pattern. You’re adapting an existing interface, and the protocol ensures your adapter will work with the target.</p><h4>Adapter Key points:</h4><ul><li>The <strong>adapter</strong> pattern allows you to reuse a class even if it lacks required components or has incompatible components with required object.</li></ul><h4>2- Composite Pattern “Tree Pattern” :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*zhBLc1c0cglcaONNsY7--Q.png" /></figure><blockquote>1- The <strong>component protocol</strong> ensures all constructs in the tree can be treated the same way.<br>2- A <strong>leaf</strong> is a component of the tree that does not have child elements.<br>3- A <strong>composite</strong> is a container that can hold leaf objects.</blockquote><p>We suppose we have a folder “Container” , that has a lot of files “Leafs” , those leafs have the same proprieties “Protocol”</p><p>//-Component Protocol</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d93efa9aa2157c3ae0079268482cd588/href">https://medium.com/media/d93efa9aa2157c3ae0079268482cd588/href</a></iframe><p>//Leafs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44e32acfc18656649fadb20f982363a/href">https://medium.com/media/e44e32acfc18656649fadb20f982363a/href</a></iframe><p>//Composite</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb8dd6a8fb4a0641fc553795f12c8cd7/href">https://medium.com/media/cb8dd6a8fb4a0641fc553795f12c8cd7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*msSxJMT25FP94lhN8o1ZMA.png" /></figure><p><strong>When should you use it?<br></strong>trying to create two types of classes for branches and nodes can make it difficult for those classes to communicate.</p><h4>Composite Key points:</h4><ul><li>This is a great pattern to help simplify apps that have multiple classes with similar features. With it, you can reuse code more often and reduce complexity in your classes.</li></ul><h4>3- Flyweight Pattern:</h4><p>The flyweight pattern is a structural design pattern that minimizes memory usage and processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*u_oyULsYiBpC9TxR1jesRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*wKPjv4Ef6qfjSQ31OR7N7w.png" /></figure><p>//MARK:- FlyWeight</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e365129a30ebf3a525d5deb0731d6186/href">https://medium.com/media/e365129a30ebf3a525d5deb0731d6186/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*Rnq7fMyzLKjugbQKXvAoJw.png" /></figure><blockquote>Note: Does this sound familiar to <strong>Singleton</strong>? It should! The flyweight pattern is a variation on the singleton pattern. In the flyweight pattern, you usually have multiple different objects of the same class.</blockquote><p><strong>When should you use it?<br></strong>Use a flyweight in places where you would use a singleton, but you need multiple shared instances with different configurations. If you have an object that’s resource intensive to create and you can’t minimize the cost of creation process, the best thing to do is create the object just once and pass it around instead.</p><h4>Flyweight Key points:</h4><ul><li>The flyweight pattern minimizes memory usage and processing.</li></ul><h4>4- Facade Pattern:</h4><p>The facade pattern is a simple pattern used to group the interfaces of a group of objects and a unified interface that is easier to use by a client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*-Tjzb3-JWTSoSmFHHJR9Iw.png" /></figure><blockquote>1- The <strong>facade</strong> provides simple methods to interact with the system.<br>2- The <strong>dependencies</strong> are objects owned by the facade. Each dependency performs Its logic</blockquote><p>Example : Assume we need to make online store , it has Products , Cart , ShippingMethod , and Customer who Pay</p><p>Products , Customer our <strong>Model<br></strong>Shipping and Cart our <strong>Dependency ,</strong> then we need facade Method to do Shopping</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abb71cb2621c9f0fa5328ea1201fe557/href">https://medium.com/media/abb71cb2621c9f0fa5328ea1201fe557/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*rZgTRK6wRf8dzgbo41E4qQ.png" /></figure><h4>Adapter Key points:</h4><ul><li>The <strong>facade</strong> provides simple methods to interact with the system. Behind the scenes, it owns and interacts with its dependencies, each of which performs a small part of a complex task.</li></ul><blockquote>Note : The facade Pattern is similar to Factory Pattern <a href="https://www.quora.com/What-is-the-difference-between-the-Facade-and-Factory-design-patterns">here is the difference</a>.</blockquote><h4>5- Decorator Pattern “<em>Wrapper design pattern</em>” :</h4><p>allows you to dynamically attach new functionalities to an object by wrapping them in useful <em>wrappers , or upgrade object </em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*EvqxPN6Xca-m_6uNRaLTUw.png" /></figure><blockquote>1- <strong>Core Component</strong> — it is the base class or protocol which our base object will subclass / implement.<br>2- <strong>Concrete Component</strong> — implemetation (or again, subclass) of <strong>Core Component</strong>.<br>3- <strong>Decorator</strong> — again implementation (or subclass) of <strong>Core Component</strong>.<br>4- <strong>Concrete Decorator</strong> — implementation of <strong>Decorator</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f394f784e0914983b13ce98d06fe5560/href">https://medium.com/media/f394f784e0914983b13ce98d06fe5560/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7402b4c23f04528c50bfaee749e9ff89/href">https://medium.com/media/7402b4c23f04528c50bfaee749e9ff89/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d23d7b6aff8edc80f6e220f038ed8a0f/href">https://medium.com/media/d23d7b6aff8edc80f6e220f038ed8a0f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4241e9f33e8ab4dcaed4485b5315e0d8/href">https://medium.com/media/4241e9f33e8ab4dcaed4485b5315e0d8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*FyrXaddN97PAyyQct6uQFA.png" /></figure><h4>You should use the Decorator design pattern?</h4><ul><li>when you want to add responsibilities to objects dynamically and conceal those objects from the code that uses them;</li></ul><h3>Conclusion</h3><p>I hope you have found this solution helpful for design pattern. I also hope that you found the information contained herein valuable enough for your own app development.</p><p>Thank you ❤️</p><p>thanks all of my friends , thanks raywenderlich.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89603d3032d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>