<?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 Andre Tirta on Medium]]></title>
        <description><![CDATA[Stories by Andre Tirta on Medium]]></description>
        <link>https://medium.com/@andretirtawijaya?source=rss-60d4938fd410------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Andre Tirta on Medium</title>
            <link>https://medium.com/@andretirtawijaya?source=rss-60d4938fd410------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:06:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andretirtawijaya/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[Making JSON Decoding Robust in Swift — My Journey Towards AutoKey Macro (Part 2)]]></title>
            <link>https://medium.com/@andretirtawijaya/making-json-decoding-robust-in-swift-my-journey-towards-autokey-macro-part-2-515448ca5180?source=rss-60d4938fd410------2</link>
            <guid isPermaLink="false">https://medium.com/p/515448ca5180</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Andre Tirta]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 08:11:15 GMT</pubDate>
            <atom:updated>2025-09-18T08:11:59.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making JSON Decoding Robust in Swift — My Journey Towards AutoKey Macro (Part 2)</h3><p>In <a href="https://medium.com/@andretirtawijaya/making-json-decoding-smarter-in-swift-my-journey-towards-autokey-part-1-530fc942345e">Part 1</a>, I introduced .convertFromAnyCase, a custom decoding strategy that made Swift models more <strong>robust</strong> against inconsistent JSON key styles. It solved the first big problem: dealing with case mismatches across APIs.</p><p>But once I started using it more broadly, two new challenges surfaced:</p><ol><li><strong>Performance on large payloads</strong> — Apple’s own documentation warns about the cost of custom key strategies, and my benchmarks confirmed the hit grows as JSON size increases.</li><li><strong>Keys that change meaning, not just case</strong> — for example, when a backend sends &quot;description&quot; but the model calls it message. This can’t be fixed by case conversion alone.</li></ol><p>To address these, I started looking beyond case strategies — drawing inspiration from how <strong>Android developers handle JSON mapping.</strong></p><p>In fact, there’s already an active discussion on the Swift forums about a <a href="https://forums.swift.org/t/the-future-of-serialization-deserialization-apis/78585/1">next-generation serialization API</a>, with performance and macro-based flexibility at its core. That confirmed I wasn’t alone: the need for more powerful, efficient, and customizable decoding is real.</p><p>This part of the journey is about bridging the gap until those future APIs arrive — experimenting with macros, building something like an <strong>AutoKey</strong> system, and pushing decoding in Swift closer to both <strong>performance and convenience</strong>.</p><p>To make the discussion concrete, let’s use the following JSON across all examples:</p><pre>{<br>  &quot;id&quot;: 42,<br>  &quot;user_name&quot;: &quot;swiftdev&quot;,<br>  &quot;description&quot;: &quot;Building macros is fun&quot;,<br>  &quot;createdAt&quot;: &quot;2025-09-18T10:30:00Z&quot;<br>}</pre><p>It’s simple yet realistic, and it covers both common challenges:</p><ul><li><strong>Mixed key styles</strong> (user_name is snake_case, createdAt is camelCase).</li><li><strong>Keys that change meaning</strong> (description in JSON maps to message in our Swift model).</li></ul><h4>1️⃣ Manual CodingKeys in Swift</h4><p>The traditional way to handle renamed keys and different styles is with CodingKeys:</p><pre>struct User: Decodable {<br>    let id: Int<br>    let username: String<br>    let message: String<br>    let createdAt: String<br><br>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case username = &quot;user_name&quot;<br>        case message = &quot;description&quot;<br>        case createdAt<br>    }<br>}</pre><h4>2️⃣ Android Inspiration</h4><p>Android developers solve this elegantly with @SerializedName (Java) or @Json(name = &quot;...&quot;) (Kotlin):</p><pre>data class User(<br>    val id: Int,<br>    @SerializedName(&quot;user_name&quot;) val username: String,<br>    @SerializedName(&quot;description&quot;) val message: String,<br>    val createdAt: String<br>)</pre><p>This inspired our AutoKey macro in Swift.</p><h4>3️⃣ AutoKey Macro in Swift</h4><p>Here’s how we achieve a similar pattern with macros:</p><pre>@AutoKey<br>struct User: Decodable {<br>    let id: Int<br>    <br>    @KeyAlias(&quot;user_name&quot;)<br>    let username: String<br>    <br>    @KeyAlias(&quot;description&quot;)<br>    let message: String<br>    <br>    let createdAt: String<br>}</pre><ul><li>@AutoKey automatically normalizes mixed key styles.</li><li>@KeyAlias handles renamed keys without boilerplate.</li><li>Decoding is <strong>fast at runtime</strong>, because the mapping work is done at <strong>compile time</strong>, unlike .convertFromAnyCase which inspects keys at runtime.</li></ul><h4>Decoding Example</h4><pre>guard let url = Bundle.main.url(/service/forresource: &quot;user&quot;, withExtension: &quot;json&quot;) else { return }<br>let data = try Data(contentsOf: url)<br>let decoder = JSONDecoder()<br>let user = try decoder.decode(User.self, from: data)<br>print(user)</pre><p><strong>Output:</strong></p><pre>User(id: 42, username: &quot;swiftdev&quot;, message: &quot;Building macros is fun&quot;, createdAt: &quot;2025-09-18T10:30:00Z&quot;)</pre><p>If you’re curious to dive deeper or try it out yourself, I’ve published the code here:<br> 👉 <a href="https://github.com/andre-tirta/auto-key">AutoKey macro on GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=515448ca5180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making JSON Decoding Smarter in Swift — My Journey Towards AutoKey (Part 1)]]></title>
            <link>https://medium.com/@andretirtawijaya/making-json-decoding-smarter-in-swift-my-journey-towards-autokey-part-1-530fc942345e?source=rss-60d4938fd410------2</link>
            <guid isPermaLink="false">https://medium.com/p/530fc942345e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Andre Tirta]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 08:10:58 GMT</pubDate>
            <atom:updated>2025-09-19T01:09:48.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making JSON Decoding Robust in Swift — My Journey Towards AutoKey Macro (Part 1)</h3><p>In most modern APIs, teams agree on a single naming convention (often <em>snake_case or </em><em>camelCase</em>) and stick with it. That’s the ideal.</p><p>But in reality, especially when working with legacy systems or micro services owned by different teams, you can end up consuming payloads that mix styles — or at least vary across endpoints. That’s where a more robust decoding strategy pays off.</p><p>In Swift, our models are written in <em>camelCase</em>. And every time we encounter different naming conventions, we have to fall back to something like this:</p><pre>struct User: Codable {<br>    let userId: String<br>    let firstName: String<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case userId = &quot;user_id&quot;<br>        case firstName = &quot;FirstName&quot;<br>    }<br>}</pre><h3>A Robust JSON Decoder</h3><p>I started with a simple helper that could load JSON test files and try decoding them into multiple model types:</p><pre>@discardableResult<br>func decodeJson(_ name: String, _ models: Decodable.Type...) -&gt; Decodable? {<br>    guard let url = Bundle.main.url(/service/forresource: name, withExtension: &quot;json&quot;) else {<br>        print(&quot;Failed to locate JSON file.&quot;)<br>        return nil<br>    }<br>    <br>    do {<br>        let data = try Data(contentsOf: url)<br>        let decoder = JSONDecoder()<br>        decoder.keyDecodingStrategy = .convertFromAnyCase<br>        for model in models {<br>            if let decoded = try? decoder.decode(model, from: data) {<br>                return decoded<br>            }<br>        }<br>    } catch {<br>        print(&quot;Failed to decode JSON: \(error)&quot;)<br>    }<br>    return nil<br>}</pre><p>The trick here is in the line:</p><pre>decoder.keyDecodingStrategy = .convertFromAnyCase</pre><p>That’s not a built-in strategy — it’s a <strong>custom extension</strong> on JSONDecoder, designed to make decoding more robust against mixed or inconsistent key styles.</p><pre>extension JSONDecoder.KeyDecodingStrategy {<br>    static let convertFromAnyCase = JSONDecoder.KeyDecodingStrategy.custom({ CodingKeys in<br>        guard let codingKey = CodingKeys.last else {<br>            return AnyKey.empty<br>        }<br>        if codingKey.intValue != nil {<br>            return codingKey<br>        }<br>        switch recognizeCase(of: codingKey.stringValue) {<br>        case .camelCase:<br>            print(&quot;codingKey: unchanged \(codingKey.stringValue)&quot;)<br>            return codingKey<br>        case .kebabCase, .snakeCase, .upperSnakeCase:<br>            let camelCased = AnyKey(string: codingKey.stringValue.convertToCamelCase())<br>            print(&quot;codingKey: from \(codingKey.stringValue) to \(camelCased.stringValue)&quot;)<br>            return camelCased<br>        case .pascalCase:<br>            guard let firstChar = codingKey.stringValue.first else { return codingKey }<br>            let camelCased = firstChar.lowercased() + codingKey.stringValue.dropFirst()<br>            print(&quot;codingKey: from \(codingKey.stringValue) to \(camelCased)&quot;)<br>            return AnyKey(string: camelCased)<br>        default:<br>            return codingKey<br>        }<br>    })<br><br>    func recognizeCase(of key: String) -&gt; CaseType {<br>        if key.contains(&quot;_&quot;) &amp;&amp; key == key.lowercased() {<br>            return .snakeCase<br>        } else if key.contains(&quot;_&quot;) &amp;&amp; key == key.uppercased() {<br>            return .upperSnakeCase<br>        } else if key.contains(&quot;-&quot;) &amp;&amp; key == key.lowercased() {<br>            return .kebabCase<br>        } else if key.first?.isUppercase == true &amp;&amp; !key.contains(&quot;_&quot;) &amp;&amp; !key.contains(&quot;-&quot;) {<br>            return .pascalCase<br>        } else if key.first?.isLowercase == true &amp;&amp; key.dropFirst().contains(where: { $0.isUppercase }) {<br>            return .camelCase<br>        } else {<br>            return .unknown<br>        }<br>    }<br>}<br><br>struct AnyKey: CodingKey {<br>    static let empty = AnyKey(string: &quot;&quot;)<br>    var stringValue: String<br>    var intValue: Int?<br>    <br>    init?(stringValue: String) {<br>        self.stringValue = stringValue<br>        self.intValue = nil<br>    }<br>    <br>    init?(intValue: Int) {<br>        self.stringValue = String(intValue)<br>        self.intValue = intValue<br>    }<br>    <br>    init(string: String) {<br>        self.stringValue = string<br>        self.intValue = nil<br>    }<br>}<br><br>enum CaseType {<br>    case snakeCase<br>    case camelCase<br>    case pascalCase<br>    case kebabCase<br>    case upperSnakeCase<br>    case unknown<br>}</pre><h3>Wait, doesn’t Swift already have .convertFromSnakeCase?</h3><p>Yes — Apple’s JSONDecoder does include a built-in strategy:</p><pre>decoder.keyDecodingStrategy = .convertFromSnakeCase</pre><p>It works if your API is strictly snake_case.</p><p>But sometimes real-world APIs aren’t always that neat. Some endpoints use PascalCase, others kebab-case, and occasionally you’ll even run into UPPER_SNAKE_CASE. Worse, sometimes a single payload mixes different styles.</p><p>That’s why I built .convertFromAnyCase:</p><ul><li>It detects whether a key is snake, pascal, kebab, upper-snake, or camel.</li><li>Then it automatically normalizes it into camelCase for your Swift model.</li></ul><p>This way, your models stay compact — even when different backend services follow different naming conventions.</p><h3>⚠️ <strong>Performance Note</strong></h3><p>Apple explicitly warns in their documentation:</p><blockquote><strong><em>Note</em></strong><em><br> Key decoding strategies other than </em><em>JSONDecoder.KeyDecodingStrategy.useDefaultKeys may have a noticeable performance cost because those strategies may inspect and transform each key.<br> — </em><a href="https://developer.apple.com/documentation/foundation/jsondecoder/keydecodingstrategy-swift.enum"><em>Apple Docs</em></a></blockquote><p>So while .convertFromAnyCase is useful, it comes with potential runtime costs.</p><h3>⚡️ Real-World Performance Test</h3><p>I wanted to see how much this actually matters. So I benchmarked decoding JSON responses of different sizes (Small → Extra Large), as well as arrays, on both a <strong>real device (iPhone X iOS 16)</strong> and the <strong>iOS 17 Simulator</strong>.</p><p>You can check the test variants and the full test results here:</p><p><a href="https://gist.github.com/andre-tirta/88e7c168794de5af1966c1203d8d5814">https://gist.github.com/andre-tirta/88e7c168794de5af1966c1203d8d5814</a></p><h3>📊 Takeaways</h3><ul><li>For <strong>small and medium payloads</strong>, the difference is negligible (&lt; 3%).</li><li>For <strong>large payloads</strong>, custom strategies start to add noticeable overhead.</li><li>For <strong>extra-large payloads</strong>, the difference is significant (+25–33%).</li></ul><p>This confirms Apple’s warning: custom decoding strategies add flexibility, but at a performance cost.</p><h3>Why This Matters (Especially for iOS Developers)</h3><p>The biggest payoff here is that we <strong>avoid manually writing </strong><strong>enum CodingKeys</strong> for every model.</p><p>For iOS developers, that’s huge. Unlike our Android counterparts, we don’t get to annotate fields with a single line. Instead, we’ve historically had to spell out every mismatch, line by line.</p><p>And here’s the catch:</p><ul><li>Case conversion strategies are great when the key is predictable (e.g. first_name → firstName).</li><li>But many times, we <strong>actually change the key</strong>.</li></ul><p>For example:</p><pre>struct ErrorResponse: Codable {<br>    let message: String<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case message = &quot;description&quot; // backend uses &quot;description&quot;, but we prefer &quot;message&quot;<br>    }<br>}</pre><p>In these situations, <strong>a custom decoding strategy is not enough</strong>. You still need to explicitly tell Swift: “this property maps to that key.”</p><p>That’s where <strong>AutoKey macro</strong> comes in.</p><h3>Looking Ahead — AutoKey and KeyAlias</h3><p>This is where things got really interesting. While building this, I couldn’t help but think:</p><ul><li>On Android, @SerializedName is concise and powerful.</li><li>On iOS, why can’t we do something similar — or better?</li></ul><p>That question is what led me to experiment with <strong>Swift Macros</strong>.</p><p>The result: <strong>AutoKey</strong> and <strong>KeyAlias</strong>, two macros that can:</p><ul><li>Automatically generate CodingKeys for you.</li><li>Allow <strong>aliasing</strong> when your property name and the backend key are semantically different (description → message).</li></ul><p>That will be the focus of <strong>Part 2</strong>, where I’ll dive into how I built those macros, and how they make JSON decoding even more seamless in Swift.</p><h3>Closing Thoughts</h3><p>This first step was all about creating a robust json decoding:</p><ul><li>A robust JSONDecoder that understands different case types.</li><li>Utilities for case conversion that keep encoding/decoding symmetrical.</li></ul><p>But as we saw, <strong>case conversion alone isn’t enough</strong>. To handle those key changes, we need something more — and that’s where AutoKey and KeyAlias come in.</p><p>Check out <a href="https://medium.com/@andretirtawijaya/making-json-decoding-robust-in-swift-my-journey-towards-autokey-macro-part-2-515448ca5180">Part 2</a> 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=530fc942345e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>