<?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 Mykola Dementiev on Medium]]></title>
        <description><![CDATA[Stories by Mykola Dementiev on Medium]]></description>
        <link>https://medium.com/@mykola.dementiev?source=rss-1d0b08a6ac5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pMq4SprpsFlqwX6y.</url>
            <title>Stories by Mykola Dementiev on Medium</title>
            <link>https://medium.com/@mykola.dementiev?source=rss-1d0b08a6ac5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:24:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mykola.dementiev/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[Swift Set: When contains(…) => true Misleads You and Hides a Broken Collection]]></title>
            <link>https://medium.com/@mykola.dementiev/swift-set-when-contains-true-misleads-you-and-hides-a-broken-collection-8077afc08ad9?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8077afc08ad9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 23:00:07 GMT</pubDate>
            <atom:updated>2026-11-20T11:30:12.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Wooden library card-catalog drawers with fixed labels" src="https://cdn-images-1.medium.com/max/1024/0*BF2zayisGFnwQdwQ" /></figure><p><em>Rewrite the surname on a card without moving it to the right drawer, and the catalog sends the next search to the wrong place. This illustrates a stale index, not literal alphabetical hashing.</em></p><p><strong>The problem:</strong></p><p>Add two users to a Swift Set, with IDs 1 and 2. Then change the first user’s ID (user.id = 2), and iterating the collection now gives [2, 2]: both stored objects compare equal. A contains check can still return true, so a quick membership test makes the mistake look harmless.</p><p>The mutation compiles because the set holds references to class instances. Another reference can change the field that defines equality without giving the collection a chance to reconsider its index. The useful question is how to expose that failure even when lookup appears to work.</p><p>Following that one assignment leads to a second surprise. “Swift picks one random seed per process” is only part of the explanation for results that change between newly created sets. We’ll use the actual output and the native lookup implementation to separate those two problems. We’ll also explain what a random seed is and how it affects hashing.</p><h3>TL;DR</h3><ul><li>Keep the fields used by == and hash(into:) stable while an object is in a Set or used as a Dictionary key. A let collection does not freeze its class instances.</li><li>A successful contains after a key mutation does not validate the collection. It can already hold two elements that compare equal.</li><li>The inspected native implementation combines a process seed with a table-specific seed. New tables can give different observations within one process; repeated lookup in one unchanged table is a different experiment.</li><li><strong>Do not persist </strong><strong>hashValue as a cache key or database ID:</strong> the same value can receive a different hash after the program restarts. Store a stable ID for an entity; for a content fingerprint, choose an appropriate stable algorithm and a defined byte representation.</li><li><strong>How to avoid the problem:</strong> prefer a stable account ID when deduplicating accounts. Use === and ObjectIdentifier when tracking live instances. If the actual key must change, remove it from every affected collection before mutation, then insert it again.</li></ul><h3>The Set already violates uniqueness, although contains returns true</h3><p><strong>Note</strong></p><p>The complete code for both versions, with the bug and with the fix, appears below, immediately after the output. User is a class whose == and hash(into:) both use id. The users set stores references to those objects; another part of the application can hold references to the same instances.</p><p>Start with IDs 1 and 2. They are unequal, so insertion keeps both. Change the first ID to 2 through that other reference. There is no reinsertion to check uniqueness. The local run prints:</p><pre>Stored IDs: [2, 2]<br>Count: 2<br>Objects compare equal: true<br>Contains first: true<br>Contains second: true<br>Every stored ID is unique: false</pre><p><strong>The collection is already broken:</strong> a Set must not contain two elements that compare equal through ==. We violated that requirement by changing the key after insertion. contains only looks for an equal element; it does not scan every stored element for duplicates. Its true therefore does not validate the mutation or the collection. Here, the duplicate IDs and Count: 2 expose the mistake.</p><p>The comparison below changes one thing. On the left, the key is changed in place. On the right, the element is removed using its old key, changed, and inserted again. <strong>Run both</strong> to compare the stored IDs and the uniqueness result.</p><p><strong>With the bug</strong></p><p>MutateInPlace.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>final class User: Hashable {<br>    var id: Int<br>    init(id: Int) { self.id = id }<br> <br>    static func == (lhs: User, rhs: User) -&gt; Bool {<br>        lhs.id == rhs.id<br>    }<br> <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}<br> <br>func changeID(<br>    _ user: User, to id: Int,<br>    in users: inout Set&lt;User&gt;<br>) {<br> <br>    user.id = id<br> <br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let first = User(id: 1)<br>let second = User(id: 2)<br>var users: Set&lt;User&gt; = [first, second]<br>changeID(first, to: 2, in: &amp;users)<br> <br>let ids = users.map(\.id).sorted()<br>print(&quot;Stored IDs: \(ids)&quot;)<br>print(&quot;Count: \(users.count)&quot;)<br>print(&quot;Objects compare equal: \(first == second)&quot;)<br>print(&quot;Contains first: \(users.contains(first))&quot;)<br>print(&quot;Contains second: \(users.contains(second))&quot;)<br>let unique = users.count == Set(ids).count<br>print(&quot;Every stored ID is unique: \(unique)&quot;)<br> <br>// ▷ Try: change the destination ID from 2 to 3 and compare membership as well as uniqueness.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VX2vUQBD%2FKkMeJIEzxRZ8CF6h9k560FrpVRCMyF4y561sdq%2FZzdVSCr756oN%2Fvol%2BHz%2BJs7ObtBV98kFqCNze%2FPnNzG9nJpdJlRTJ1hb8%2BPzxTr%2Bl9kV8%2BQZ7J6ez%2FcMpTF%2FsHT07nBbgVgiVqRFqaavOWqxBapaK1slKYXD91wX8df2lXkotFFRKWAvPLbYFHAi7EguFcFlqoGcjWpB1ATPtgkBq6dIoyeASLKplLmsYkxlceVBvZZ0gpmDZ6QrGY0jVyhYcYQRtf8zg%2Fi48Nkb1sfxDhow29nZ0CpoBlwFXlGMqtTN88llLbTrHuXvYG3DBIK9Ms5AaKe9sAGRMxqtWQr%2FB2SQNutfQMRUhXYoSqx31BLDe9lHn6B55091SD6G9QU9KjOQ75tP7O%2F2GIr5%2BgMn06BgO9k6eTufzArRxsKbJALPkIcF3olkrzGFGIq0uoO20HYaKQQDEwmxonnQN65auMuhbtJ1yOezzhYB0sGwRCSGOH9bSmTb%2FT8gstWzWhnh7Yjpd07wY7YXMR1omfjXNnedVOCjLdCIc5tqcZyVZJZk3VUgMydY6ajTfgjyXD7KgsFgZXd%2FUbJPGz3Ns36FxyeYlw4yi06tSDzMRFc6Q%2F4guooB77D8kIGtLACzLG7FOy5I6P8stVYZ1ml0XNKe7o1U6m1Bsqof8Mq6j1%2B8TDY5VAazy%2F2%2BbHC%2FeYkXNQvNMHUcNcdYJxS6RhnGs4Fdk7YSkJmSrWyGCIrhnf%2FAKkL9zi8GCnyej0%2FKsw4EPLsFnRVxzwUFyHWO6wfaCtmVkBqSNECEaH7N42%2Fy5%2Bg6n7UURVxYPRY3W0Rr37eMRlq1pYNuvrR0er56qBpsFpbSSaxAWzlEp%2FxsiaLSWpioZJRv6tj%2FMd5KrnwGglmPnBwAA">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?runnableCode_state=run#runnable-mutate-in-place">Run this example on the site →</a></p><p><strong>Fixed</strong></p><p>RemoveThenInsert.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>final class User: Hashable {<br>    var id: Int<br>    init(id: Int) { self.id = id }<br> <br>    static func == (lhs: User, rhs: User) -&gt; Bool {<br>        lhs.id == rhs.id<br>    }<br> <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}<br> <br>func changeID(<br>    _ user: User, to id: Int,<br>    in users: inout Set&lt;User&gt;<br>) {<br>    users.remove(user)<br>    user.id = id<br>    users.insert(user)<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let first = User(id: 1)<br>let second = User(id: 2)<br>var users: Set&lt;User&gt; = [first, second]<br>changeID(first, to: 2, in: &amp;users)<br> <br>let ids = users.map(\.id).sorted()<br>print(&quot;Stored IDs: \(ids)&quot;)<br>print(&quot;Count: \(users.count)&quot;)<br>print(&quot;Objects compare equal: \(first == second)&quot;)<br>print(&quot;Contains first: \(users.contains(first))&quot;)<br>print(&quot;Contains second: \(users.contains(second))&quot;)<br>let unique = users.count == Set(ids).count<br>print(&quot;Every stored ID is unique: \(unique)&quot;)<br> <br>// ▷ Try: change the destination ID from 2 to 3 and compare membership as well as uniqueness.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91WX2vUQBD%2FKkMeJIEzxRZ8CF6h9k560FrpVRCMyF4y561sdq%2B7m6ulFHzz1Qf%2FfBP9Pn4SZ2eTtBV98kFqCCTZmfnNzG%2Fnt3eXSZUUydYW%2FPj88U7fpQ5NfPkGeyens%2F3DKUxf7B09O5wW4FcIlakRaumq1jmsQWpeFdbLSmEM%2FdcN%2FHX%2FpV5KLRRUSjgHzx3aAg6EW4mFQrgsNdC1ERZkXcBM%2B7ggtfRpt5LBJThUy1zWMCY3uAqgwct5QUzBstUVjMeQqpUrOMMIbP%2Bawf1deGyM6nOFixwZbRz86C1aBlwGXFGNqdTe8FuoWmrTeq49wN6Aiw55ZZqF1Eh1ZwMgYzJetRL6Dc4mabS9hpapiOVSlq7bUU8A212fdY7%2BUXDdLfWQmh1yi43ZYBo%2Bsuv1nqybnlLTw%2FeeXFmYsE%2Fv7%2FQdm%2Fj6ASbTo2M42Dt5Op3PC9DGw5qUBGbJosJ3olkrzGFGS1pdgG21G0TIIABiQVSC0DWsLW19tFt0rfI57PMGgvSwtIiE0MkVa%2BmNzf8TMkstm7Uh3p6YVtekL6PDIvORlkk4yuY%2B8Co8lGU6ER5zbc6zkrySLLgqJIakdZ4GMIws6%2FhBFg0OK6Prm5ZtsgT9d%2BM%2BDDr5vGSYURf0qtSDhjqDNxQ%2Foo0o4B7HDwXI2hFAnPtGrNOyJEVkuaPOsE6z64bmtHd09M4mlJv6obiM%2B%2Bjt%2B0SDZ1MEq8L3bZfjxVusaFhI%2FzRxNBBnrVAc0tEw7jr4FVl7QZqMZN1KEQ0xPPtDVIT8XViXLMYFMlotz1oc%2BOAWQlXENTccV65zTDdoL%2Bh07ZgB6TqImI1fs263%2BeftO5zai6I74lgUNTpPx34Yn4CwtKaB7XDM7bC8eqoabBZU0kquQTg4R6XCM2bQ6BypKhklG%2Fov8DDfSa5%2BAlVC%2FI8XCAAA">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?runnableCode_state=run#runnable-remove-then-insert">Run this example on the site →</a></p><p>What changed</p><p>MutateInPlace.swift → RemoveThenInsert.swift</p><pre>final class User: Hashable {<br>     var id: Int<br>     init(id: Int) { self.id = id }<br> <br>     static func == (lhs: User, rhs: User) -&gt; Bool {<br>         lhs.id == rhs.id<br>     }<br> <br>     func hash(into hasher: inout Hasher) {<br>         hasher.combine(id)<br>     }<br> }<br> <br> func changeID(<br>     _ user: User, to id: Int,<br>     in users: inout Set&lt;User&gt;<br> ) {<br>+    users.remove(user)<br>     user.id = id<br>+    users.insert(user)<br> }</pre><figure><img alt="Two LEGO desks compare mutate with two id = 2 files and reinsert with one id = 2 file" src="https://cdn-images-1.medium.com/max/1024/0*sH7S54AvDWE4R1WK" /></figure><p><em>On the left, changing the key in place leaves two equal members. On the right, removal before mutation and reinsertion keep one equal member. Reinsertion does not merge the users’ fields.</em></p><p>Reinsertion checks equality again. Because the destination ID already exists, the corrected example keeps one member for it. This example intentionally accepts keeping one equal member; it does not merge the users’ fields. An application that forbids ID conflicts should reject the change instead. For an account model, an immutable account ID is usually the cleaner design.</p><p><strong>The interesting detail:</strong> on the corrected side, contains(first) can still be true even if the set kept the already-present second instance. contains checks equality, not whether that exact reference is stored. Here the stored count and IDs confirm that only one equal member remains.</p><p>Removal must happen <strong>before</strong> mutation. Removal also performs a lookup, so changing the key first can make that operation miss as well. If several collections hold the same object, every affected collection needs to release the old key before it changes. The comparison owns only the one set shown.</p><h3>The reference stayed put; the lookup key changed</h3><p><strong>The problem explained:</strong> for this example, think of a hash table as numbered storage slots, or <em>buckets</em>. Insertion uses a hash to choose a starting bucket, checks for an equal element, and finds somewhere to store the new element. Lookup follows the corresponding search procedure.</p><p>With a class, the stored element is a reference. Assigning user.id = 2 changes the object reached by that reference. It does not call an insertion or removal method on the set. The reference remains in the slot selected when the object’s key was 1.</p><p>Now contains(user) hashes the current key, 2. That search can start somewhere else and reach an empty bucket before it reaches the stored reference. The object hasn’t disappeared; the lookup no longer follows the route used to place it.</p><figure><img alt="A LEGO file labelled id = 2 remains in slot 1 while slot 2 is empty" src="https://cdn-images-1.medium.com/max/1024/0*Ru42zYzlm51KOPtH" /></figure><p><em>The label changed; the file stayed put. A search based on the new key can look in the empty slot instead.</em></p><p>🔎 <strong>What to watch:</strong> follow <strong>User u</strong>. Its id changes while the reference in <strong>Bucket [1]</strong> stays put. Then <strong>Lookup</strong> follows the new key to the empty <strong>Bucket [2]</strong>.</p><figure><img alt="A reference inserted under id 1 still points to the same mutated object. Lookup with id 2 can stop at an empty bucket." src="https://cdn-images-1.medium.com/max/1024/0*Uohd-Tt_URxKnISk.png" /><figcaption>The key changes; the stored reference stays put</figcaption></figure><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?diagramPlayer_state=play#diagram-mutated-key">Play the animation on the site →</a></p><p>This is a four-bucket teaching model with invented hashes (105 and 202). It isolates the reference and the two search routes; the native implementation comes next.</p><p>Two requirements matter here:</p><ol><li><strong>Equality and hashing must agree.</strong> Values that compare equal must feed the same essential components to Hasher, in the same order. That is the <a href="https://developer.apple.com/documentation/swift/hashable">documented Hashable requirement</a>.</li><li><strong>Do not change the key while it is in the collection.</strong> The equality-defining components must stay stable while an element is stored in the set.</li></ol><p>The User implementation agrees with itself at each instant: both methods read id. <strong>The mistake is changing that key while the collection still indexes the old state.</strong> Making the collection a let constant does not freeze the fields of a class instance inside it. Copying a Set also doesn’t make independent copies of those instances.</p><h3>Why contains(…) can return true after a key change</h3><p>With one element, the same mistake can be harder to recognize. The object is still visible during iteration, but hash-based lookup may return false. In another run it may return true.</p><p><strong>Tip</strong></p><p><strong>Try it yourself:</strong> run the program below several times with <strong>Run</strong>, or choose <strong>Open in the online editor</strong> → <strong>Run</strong>. Compare Hash-based lookup with Same instance found by iteration: lookup can change between true and false across executions, while iteration finds the same instance. Seeing both results within a few attempts is not guaranteed; repeated true results do not make the mutation safe either.</p><p>MutationLookup.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>final class User: Hashable {<br>    var id: Int<br>    init(id: Int) { self.id = id }<br> <br>    static func == (lhs: User, rhs: User) -&gt; Bool {<br>        lhs.id == rhs.id<br>    }<br> <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let user = User(id: 1)<br>let users: Set&lt;User&gt; = [user]<br>user.id = 2<br> <br>print(&quot;Count: \(users.count)&quot;)<br>print(&quot;Stored IDs: \(users.map(\.id).sorted())&quot;)<br>print(&quot;Hash-based lookup: \(users.contains(user))&quot;)<br>let found = users.contains { $0 === user }<br>print(&quot;Same instance found by iteration: \(found)&quot;)<br> <br>// ▷ Try: change id to another number; a successful lookup does not validate the mutation.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VS2%2FTQBD%2BKyOLgy21Lg%2BJgyGVQhLUSC2gpkhImMPaHpMV69loH4EqqsSNKwce%2FwT%2BD7%2BE2bUTkjMHVCxLXs9%2B%2B83D34w3SZ0UyckJ%2FPr6%2BVbfJYUkvv2A8eXVfHI%2Bg9mr8cWL81kBbolQ6wahkbb21mIDkqJVGCdrhf3Rf53AX%2BdfUitJKKiVsBZeWjQFnAm7FJVC2JQEfK2FAdkUMCfXGyRJlw6WDDZgUbW5bGDEMLgJpAFlneBKQeuphtEIUrW0RfRwBGa7zOD4FJ5orba%2BwsXAyDYKOF71OzveSLjkGFNJTsdViFqS9i7GHmj36HpAXuuukoQcd7YjjJzhO375eKvvPonvn2A6u3gOZ%2BPLZ7PFogDSDlasV9BtlC5%2BEN1KYQ5zNpG6BuPJ7qQeSQBEpdescmpgZbjA%2Fb5B65XLYbIU9BZBOmgNIjMMTYGNdNrk%2F0kxS5LdSnPdnmpPDatYUzDGeqRlEgbGwoW6CgdlmU6Fw5z0%2B6xkVJIFqEIHnvXNLRFkHpvlXvbHzvJfoHsc9k4Z8zrY3pQUHn0j3d93OOEwXBFcxbMsZX7PoqstZMHl5xk1n9o9XCdWaVkyYZZbTgebNDs8FbrluBJhuimt3%2FnVgRNyQpKNr8O5EH4basIRHqJ4Cty5yy3b20Nv7SITHQuGeBpQjcPpioXj0MTKRpfRnA3FizP5J1yZ6wLqQXANcKsLFjS3MpDvKjSPQID1dY3Wtl4NCUCj0Ubhr4WS%2FO0w6rPzLjpjhSZHyZr%2FXg%2FzB8nNb4ZQYqDJBgAA">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?runnableCode_state=run#runnable-mutation-lookup">Run this example on the site →</a></p><p>One recorded run printed Count: 1, Stored IDs: [2] and Hash-based lookup: false, while iteration still found the exact instance. Iteration follows the stored references; contains(_:) searches using the current key. The iteration check is a diagnostic here, not a repair for the invalid index.</p><p>Suppose our teaching table has four buckets. An insertion with an invented hash of 105 starts at bucket 105 % 4, which is 1. After mutation, consider two possible hashes:</p><p><strong>Hash of the new key:</strong> 202; <strong>Starting bucket:</strong> 2; <strong>What happens in this one-element model:</strong> The bucket is empty, so the lookup misses.</p><p><strong>Hash of the new key:</strong> 309; <strong>Starting bucket:</strong> 1; <strong>What happens in this one-element model:</strong> The lookup reaches the stored reference; == reads the current IDs, 2 == 2, and succeeds.</p><figure><img alt="Pigeons occupying some of the compartments in a wooden pigeon loft" src="https://cdn-images-1.medium.com/max/1024/0*IlQhV8N8UX_IApZq" /></figure><p><em>A finite set of slots cannot give every possible hash a unique starting slot. Two different full hashes can select the same bucket.</em></p><p><strong>The pigeonhole principle:</strong> more possible inputs than output slots means some inputs share a slot. It does <strong>not</strong> mean Swift has to store two elements in one physical bucket; probing resolves occupied positions.</p><p>105 and 309 are different hashes. What matches is their <strong>starting bucket</strong>, after mapping a much larger hash range into four slots. This distinction avoids making the explanation depend on finding a collision between two complete hash values.</p><p>Swift’s native implementation uses a power-of-two bucket count and computes the starting index with hashValue &amp; bucketMask. It then probes occupied buckets, compares elements through ==, and continues until it finds a match or an empty slot. See <a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/HashTable.swift">idealBucket in HashTable.swift</a> and <a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/NativeSet.swift">find in NativeSet.swift</a>.</p><p>The positive-number % 4 example illustrates the mapping; it is not a recipe for recovering a real bucket from user.hashValue. A set also supplies its own seed, and public Set.capacity is not the number of buckets.</p><p>With more occupied buckets, probing creates additional routes to a match. A successful contains call therefore tells us little about the correctness of this mutation. The test may have taken a route that happened to reach the reference.</p><h3>Why can new sets disagree within one process?</h3><p><strong>Why does Swift need a random seed?</strong> To make it harder for an attacker to choose keys that overwhelm an application. With predictable hashing, an attacker can prepare many distinct keys with collisions and feed them to the program. A lookup or insertion that averages O(1) can require O(n) comparisons; a series of n insertions can take up to O(n²) work. The CPU spends its time processing those inputs, leaving the application unresponsive or the service unable to keep up with requests. This is <strong>hash flooding</strong>, a form of denial of service described in the <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0206-hashable-enhancements.md">motivation for SE-0206</a>.</p><p><strong>A seed is a random starting value for hashing</strong>, normally chosen when the Swift process starts. Another seed can distribute the same keys differently, making a collision set prepared for one execution harder to reuse in another. This protects against predictable collision patterns; collisions remain possible. A correct collection also checks keys with ==: collisions can slow lookup, but do not by themselves make it return another key’s data.</p><p><strong>When did Swift introduce this?</strong> General randomized hashing in the standard library and the public Hasher arrived with <strong>Swift 4.2</strong>, as recorded in <a href="https://developer.apple.com/documentation/xcode-release-notes/swift-4_2-release-notes-for-xcode-10">Apple’s release notes</a> and <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0206-hashable-enhancements.md">SE-0206</a>. “There was no seed anywhere before 4.2” would be too broad: for example, Swift 4.1 already used randomly seeded SipHash for String on non-Apple platforms. <a href="https://forums.swift.org/t/how-is-synthesized-hashable-implemented/15960/4">Karoy Lorentey, the implementation’s author, documented that exception</a>.</p><p>Now test whether one process seed explains the whole experiment. Create new sets inside the same process. One optimized execution produced this sequence for ten short-lived tables:</p><pre>F T T F F F F F F F</pre><p>T means contains returned true; F means false. The process did not restart between these attempts. In that same execution, 64 tables kept alive together produced 36 true results and 28 false results. Those are observed counts, not probabilities promised by Swift.</p><p>The distinction between the experiments matters:</p><p><strong>One set:</strong> Repeat lookup in the same table and hash context.</p><p><strong>New short-lived sets:</strong> Storage may be released between attempts.</p><p><strong>New sets kept alive:</strong> Separate tables without immediate storage reuse.</p><p><strong>A fresh process:</strong> A new execution seed and new tables.</p><p>The next program runs the first three cases and hashes the same string twice. It is sequential, so a data race is not part of this experiment. Your output can differ from the recorded sequence.</p><p>SeedExperiment.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>final class User: Hashable {<br>    var id: Int<br>    init(id: Int) { self.id = id }<br> <br>    static func == (lhs: User, rhs: User) -&gt; Bool {<br>        lhs.id == rhs.id<br>    }<br> <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}<br> <br>func shortLivedTables() -&gt; String {<br>    var results: [String] = []<br>    for _ in 0..&lt;10 {<br>        let user = User(id: 1)<br>        let users: Set&lt;User&gt; = [user]<br>        user.id = 2<br>        results.append(users.contains(user) ? &quot;T&quot; : &quot;F&quot;)<br>    }<br>    return results.joined(separator: &quot; &quot;)<br>}<br> <br>func retainedTables() -&gt; String {<br>    var tables: [Set&lt;User&gt;] = []<br>    var users: [User] = []<br>    for _ in 0..&lt;64 {<br>        let user = User(id: 1)<br>        tables.append([user])<br>        users.append(user)<br>    }<br>    for user in users { user.id = 2 }<br>    return zip(tables, users).map { table, user in<br>        table.contains(user) ? &quot;T&quot; : &quot;F&quot;<br>    }.joined(separator: &quot; &quot;)<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let user = User(id: 1)<br>let users: Set&lt;User&gt; = [user]<br>user.id = 2<br>let repeated = (0..&lt;10).map { _ in<br>    users.contains(user) ? &quot;T&quot; : &quot;F&quot;<br>}.joined(separator: &quot; &quot;)<br>print(&quot;One table: \(repeated)&quot;)<br>print(&quot;Short-lived tables: \(shortLivedTables())&quot;)<br>print(&quot;Retained tables: \(retainedTables())&quot;)<br>print(&quot;Same string, twice:&quot;)<br>print(&quot;Swift&quot;.hashValue)<br>print(&quot;Swift&quot;.hashValue)<br> <br>// ▷ Try: run again; keep key-stability tests separate from these intentionally invalid lookups.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91WzU7bQBB%2BlZFPthQMtBUHl1BRCAIJSkXSqhJGaGNvyBZn1%2FKuQ1OE1FuvPfTnTdr36ZN0ZtdO4iBIqx4qalmJPTP7zczn2c%2B%2B9hIv8lZX4eeXTw%2F6jCU18fU7bJ%2F0DnYOO9B5s3308rATgRlySFTKIRU6KbXmKQhprawwIsm4W%2FqvG%2Fjr%2FmM5EJJlkGRMa3ileRHBPtND1s84XMcS8BizAkQawYE0ziCkMH5lCeAaNM8GoUihjWFwQ6AUpQ1DpmBQygTabfCzoY5shhYU9WUAK1vwXKmszkUHBlq0NsXhlfNMcS3gEGv0hTTKXlHVQqrS2NoJdg7OBYSJGvWF5Fh3MAW0mBZPD1VhDsWYpz1qXfu2sq4phLyY56HguswMVn%2FqfGfY9OlZVZgq4JzGZC0MN9fXGi1xAyX2i9HUtiVvPbjtR%2BAuN5sUs0XIZDubhdGtI%2FrRzFiVFLI85zL1LQx2Kw0TUtvbAJ5B7PViDyL834u9GQMOwJSFnOK8VUhT6mues4IZVdAasGtmdOESRlH3k2Wsl7iqe5qniyKqnk%2FJeSeVG0%2F%2BhEqXtGbDMRg0KWxw1eSCElt0zG1DcbznWF%2Bg7L3IfZev5aKDcMRyXGKNrRppobglD6eqZ9lzIPn5%2FOFBn66Jbx9ht3N0DPvbJy863W4EUhnAng2ogVVc%2Fo6NcqQNDtAkswkUpdRThbYgAKyvxijOMoUcx9A4vxvpEHaGTF5wEAYGBeeIUGk5TwUSG%2F4nZMZSjHKUMdhTpUxRfJUko%2BXDjz16z3UN8coMxLG%2FywwPpboKYoyisYrlXXtriTw1ZIliC55zRCeL78Sw3hjn0%2B3wOzqFo37PNqgbO5bcbayI2qpzB42YLun7SkYCP5UlDL4t%2B81lJ5XOza9Z1L6FRGzE8dVHUtgCcyUSHjX9V2JgYi%2Bkt9JrlpV8ia%2F6RPkBvWIS0eQDu8D0T%2BGS8xx%2FJiv4nu2LTJgJGK5x8CumOM66GtGYa5x8abikgWCZnf4xy%2FB5ZUpdlrnG%2Bfda3hg%2F6TbCx97NL1TSEbPeCQAA">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?runnableCode_state=run#runnable-seed-experiment">Run this example on the site →</a></p><figure><img alt="Three Enigma rotors with alphabet rings in their housing" src="https://cdn-images-1.medium.com/max/1024/0*CcAKm11X0VDobPMM" /></figure><p><em>Starting configuration is the useful analogy here: the same input can be transformed differently under another configuration. Unlike advancing Enigma rotors, an unchanged Swift table does not switch its hash context on each lookup.</em></p><p>There really is a per-execution seed. Ordinary Hasher() uses it, and hashing the same components repeatedly in one execution produces the same result. Native collections add another input: NativeSet.hashValue(for:) passes _storage._seed when hashing an element.</p><p>In the <a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/HashTable.swift">source revision inspected here</a>, normal table seeding uses the storage object’s address, which is combined with the execution seed. Copy-on-write copies can preserve an existing seed; new storage and resizing can establish a new one. That gives us a reason to distinguish repeated lookup from repeated table creation.</p><p>🔎 <strong>What to watch:</strong> <strong>Process seed</strong> is shared within this execution. Follow its combination with <strong>Table seed A</strong> and <strong>Table seed B</strong>. Repeated <strong>Lookup</strong> in one unchanged table reuses its context; creating another table can introduce a different one.</p><figure><img alt="The execution seed combines with each table seed. Separate live tables can hash the same key in different contexts." src="https://cdn-images-1.medium.com/max/1024/0*4QgMSSr0_LwhA7d4.png" /><figcaption>One process, two collection-specific hash contexts</figcaption></figure><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?diagramPlayer_state=play#diagram-hash-seeds">Play the animation on the site →</a></p><p>Implementation model for the linked Swift revision; different contexts can also produce the same lookup result.</p><p>The important result is that <strong>new sets can give different answers within one process</strong>. It does not mean repeated lookups of the same unchanged table randomly alternate between true and false.</p><p><strong>How this was tested: Swift 6.4.2, 20 runs, and limitations</strong></p><p>The local experiment used Apple Swift 6.4.2 in Swift 6 language mode, both without optimization and with -O. Five fresh processes per configuration, with default and deterministic hashing, made 20 experimental processes. The browser runner may use another toolchain.</p><p>Repeated results in a short-lived loop are consistent with an allocator reusing released storage addresses. Addresses were not measured here, so this is an inference, not an allocator trace. Keeping 64 tables alive removes immediate reuse of their released storage as an explanation for that case.</p><p>The source links pin the inspected Swift revision. They do not claim that the installed Apple toolchain was built from that exact revision. These table-seeding details explain the observed behavior; stable equality and hash fields remain the rule the model must satisfy.</p><h3>Randomization protects the table; it doesn’t repair a changed key</h3><p><strong>Do not persist </strong><strong>hashValue as a cache key or database identity.</strong> For a business entity, store its stable identifier. For a content digest, choose a suitable stable algorithm, such as SHA-256, over a defined byte representation. Those solve different problems, and neither makes an in-place change to an indexed key safe.</p><p>The reason is the initial hashing configuration: the same value can receive another hashValue after a restart. The algorithm itself can also change between standard library versions; the inspected implementation uses SipHash-1-3. The <a href="https://developer.apple.com/documentation/swift/hasher">Hasher documentation</a> explicitly warns against reusing hash values across program executions.</p><p>For local diagnostics, launch the compiled program with:</p><pre>SWIFT_DETERMINISTIC_HASHING=1 ./seed-experiment</pre><p>Set the variable before the process starts. In my deterministic runs, all the mutated-key membership checks returned false. That is another observation for this toolchain, not a new requirement to build into your tests. The variable changes seeding; the key mutation remains incorrect.</p><h3>Decide what “the same user” means</h3><p>Decide what your Set should treat as a duplicate. Two Account objects with the same stable ID usually represent one account, so the set should keep one of them. Two separate sessions for that user may be different elements even when their accountID values match. The choices below and the runnable example show how to preserve the uniqueness you need without tying lookup to a field you change.</p><p><strong>The same account, even when loaded as another instance:</strong> Equality and hashing based on a stable, immutable account ID.</p><p><strong>A selected account’s ID, while its loaded data changes:</strong> A Set&lt;User.ID&gt; alongside separately stored models.</p><p><strong>Exactly the same live object instance:</strong> === for equality and ObjectIdentifier(self) for hashing.</p><p><strong>A value whose actual key must change:</strong> Remove it using the old key, change it, then insert it again in every affected collection.</p><p>The next example contrasts the first and third choices. Change an account’s display name: its stable ID still makes a newly loaded equivalent account findable. Then change a session’s account ID: reference-based membership still recognizes that exact session, while a second session remains a different element.</p><p>IdentityModels.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>final class Account: Hashable {<br>    let id: Int<br>    var displayName: String<br> <br>    init(id: Int, displayName: String) {<br>        self.id = id<br>        self.displayName = displayName<br>    }<br> <br>    static func == (lhs: Account, rhs: Account) -&gt; Bool {<br>        lhs.id == rhs.id<br>    }<br> <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(id)<br>    }<br>}<br> <br>final class Session: Hashable {<br>    var accountID: Int<br>    init(accountID: Int) { self.accountID = accountID }<br> <br>    static func == (lhs: Session, rhs: Session) -&gt; Bool {<br>        lhs === rhs<br>    }<br> <br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(ObjectIdentifier(self))<br>    }<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let account = Account(id: 1, displayName: &quot;Jim&quot;)<br>let accounts: Set&lt;Account&gt; = [account]<br>account.displayName = &quot;Jim Halpert&quot;<br>let reloaded = Account(id: 1, displayName: &quot;James&quot;)<br>print(&quot;Reloaded account found: \(accounts.contains(reloaded))&quot;)<br> <br>let session = Session(accountID: 1)<br>let other = Session(accountID: 1)<br>let sessions: Set&lt;Session&gt; = [session, other]<br>session.accountID = 2<br>print(&quot;Separate sessions stored: \(sessions.count)&quot;)<br>print(&quot;Same session found: \(sessions.contains(session))&quot;)<br>print(&quot;New session found: \(sessions.contains(Session(accountID: 2)))&quot;)<br> <br>// ▷ Try: give the reloaded account another ID, then compare it with the separate session behavior.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE92WzWrbQBDHX2XQSQJXISn0IOqAG7vEJR8lyqFQ9bCWRtEWedfsrp2GEOit1x768Sbt%2B%2FRJOrta2bKapoUWSmoMlmZnZvf%2Fk%2BaPr4M8SIKdHfj28f29%2FmbCivj0BUZn59ODowlMXoyOnx9NEjAVQi4LhILrfKk1FsCFizJleF5jU%2FqvBfyx%2FkyUXLAa8pppDaM8l0thEjhkumKzGuE6E0CfGg3wIoGpME1gxZRFs6jZ1QmbYwKpUVxc2IZ2mQtuQl8wuC0xajvbj8a6jHkBQ9qjF%2B2U0nLnrsm7aTfUhtFjgXIpchgOIawrnbRyBqA6dxE82IcnUtbdE1C6O8DQpsbtKdbdXduKmIRcGOmuUCWkUi6NY4VqS1CTEOdyPuMCCUS0bnjTZ56i1lyKH5lbxKw583TcQe%2FYbi%2FQ5g2udZhgba7vpuQP4Cn5u59RojLH6O8COp29xtxMCxSGlxxVaMVEPWh23j68vdffRsTndzCeHJ%2FC4ejsZJKmCQhpYEG%2BArJ0FoNv2HxRYwxTCon6CtRS6LUluSYAbCZX5EaigAUNlGnWFeplbWI4qJi4QOAGSoVIHbx5YcGNVPF%2FAjMTfL6QxO0pvegFvdpS2KDjEWaBNfbUWK7MQJaFY2YwFvIyyigriGyq9TU%2FJzQx3iGcce32bCsLnvG5q%2BrUuHkxj33dPrV46VdeZcJf9SzM9aGRqBeoTBY07RTWkhVY%2FPoM9KvdKVqRZ21pK6O0LBKrtz0kjZkwjAsdtvvQaG3062biaW8%2F%2B11z2fWCJb096u4U38cz8YmOiW4dxnUhND6wZVd7G00p0jTQw1q3JOOSChtVbSxu3HwLRmoZt3o2IDolHoSPRNvlJ3j5W9W3QNiL1kzdX4qvcK6uErjgNKPNYPYeExMN0ul4YBMEjfacVLuZveSmclW6BwJmWLEVdxMcDIIV%2FQt7FD8Mbr4DMgNGwZEJAAA%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/?runnableCode_state=run#runnable-identity-models">Run this example on the site →</a></p><p>Using ObjectIdentifier requires matching identity-based equality. Hashing by instance identity while comparing two different instances as equal by account ID would break the agreement between equality and hashing. Apple’s <a href="https://developer.apple.com/documentation/swift/objectidentifier">ObjectIdentifier documentation</a> also limits meaningful identity comparisons to the instance’s lifetime; this is not a persistent account identifier.</p><p>A mutable class can be a perfectly useful set element when its equality-defining state is stable. Changing displayName is fine in the account example because that property participates in neither equality nor hashing. This says nothing about concurrent access: synchronization is a separate concern.</p><p>When testing a model like this, check that an equivalent freshly loaded account is found, that changing non-key fields preserves membership, and that separate identity-based objects remain separate. Test key changes through the collection operation that owns them. Avoid tests that require a particular numerical hash or a particular outcome after violating the key-stability requirement.</p><p><strong>What to check in your own code:</strong></p><ol><li>Open your type’s == and hash(into:) implementations. List the properties they read, such as id.</li><li>For an account ID, make it immutable: let id. Names and other fields may change if they do not participate in equality or hashing.</li><li>To track individual live instances, use === together with ObjectIdentifier(self), as in the Session example above.</li><li>If the actual key must change, first remove the object from every Set or Dictionary where it is an element or key. Only then change the field and insert it again. Decide beforehand what happens when the new ID is already taken: reject the change or keep one equal element.</li><li>In tests, check the element count and IDs as well as contains. A non-key change should preserve membership; a controlled key change should not leave two equal stored elements.</li></ol><h3>Additional resources</h3><ul><li>Cover photograph: <a href="https://commons.wikimedia.org/wiki/File:Card_catalogue_drawers.jpg">Card catalogue drawers</a>, Carolina Prysyazhnyuk, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC BY-SA 2.0</a>. Resized and converted to WebP.</li><li>Pigeon-loft photograph: <a href="https://commons.wikimedia.org/wiki/File:Pigeons-in-holes.jpg">Pigeons-in-holes</a>, BenFrantzDale, <a href="https://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0</a>. Resized and converted to WebP.</li><li>Enigma photograph: <a href="https://commons.wikimedia.org/wiki/File:Enigma_rotors_with_alphabet_rings.jpg">Enigma rotors with alphabet rings</a>, TedColes, <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0 1.0</a>. Resized and converted to WebP.</li><li>Code examples in the online editor: <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VX2vUQBD%2FKkMeJIEzxRZ8CF6h9k560FrpVRCMyF4y561sdq%2FZzdVSCr756oN%2Fvol%2BHz%2BJs7ObtBV98kFqCNze%2FPnNzG9nJpdJlRTJ1hb8%2BPzxTr%2Bl9kV8%2BQZ7J6ez%2FcMpTF%2FsHT07nBbgVgiVqRFqaavOWqxBapaK1slKYXD91wX8df2lXkotFFRKWAvPLbYFHAi7EguFcFlqoGcjWpB1ATPtgkBq6dIoyeASLKplLmsYkxlceVBvZZ0gpmDZ6QrGY0jVyhYcYQRtf8zg%2Fi48Nkb1sfxDhow29nZ0CpoBlwFXlGMqtTN88llLbTrHuXvYG3DBIK9Ms5AaKe9sAGRMxqtWQr%2FB2SQNutfQMRUhXYoSqx31BLDe9lHn6B55091SD6G9QU9KjOQ75tP7O%2F2GIr5%2BgMn06BgO9k6eTufzArRxsKbJALPkIcF3olkrzGFGIq0uoO20HYaKQQDEwmxonnQN65auMuhbtJ1yOezzhYB0sGwRCSGOH9bSmTb%2FT8gstWzWhnh7Yjpd07wY7YXMR1omfjXNnedVOCjLdCIc5tqcZyVZJZk3VUgMydY6ajTfgjyXD7KgsFgZXd%2FUbJPGz3Ns36FxyeYlw4yi06tSDzMRFc6Q%2F4guooB77D8kIGtLACzLG7FOy5I6P8stVYZ1ml0XNKe7o1U6m1Bsqof8Mq6j1%2B8TDY5VAazy%2F2%2BbHC%2FeYkXNQvNMHUcNcdYJxS6RhnGs4Fdk7YSkJmSrWyGCIrhnf%2FAKkL9zi8GCnyej0%2FKsw4EPLsFnRVxzwUFyHWO6wfaCtmVkBqSNECEaH7N42%2Fy5%2Bg6n7UURVxYPRY3W0Rr37eMRlq1pYNuvrR0er56qBpsFpbSSaxAWzlEp%2FxsiaLSWpioZJRv6tj%2FMd5KrnwGglmPnBwAA">MutateInPlace.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91WX2vUQBD%2FKkMeJIEzxRZ8CF6h9k560FrpVRCMyF4y561sdq%2B7m6ulFHzz1Qf%2FfBP9Pn4SZ2eTtBV98kFqCCTZmfnNzG%2Fnt3eXSZUUydYW%2FPj88U7fpQ5NfPkGeyens%2F3DKUxf7B09O5wW4FcIlakRaumq1jmsQWpeFdbLSmEM%2FdcN%2FHX%2FpV5KLRRUSjgHzx3aAg6EW4mFQrgsNdC1ERZkXcBM%2B7ggtfRpt5LBJThUy1zWMCY3uAqgwct5QUzBstUVjMeQqpUrOMMIbP%2Bawf1deGyM6nOFixwZbRz86C1aBlwGXFGNqdTe8FuoWmrTeq49wN6Aiw55ZZqF1Eh1ZwMgYzJetRL6Dc4mabS9hpapiOVSlq7bUU8A212fdY7%2BUXDdLfWQmh1yi43ZYBo%2Bsuv1nqybnlLTw%2FeeXFmYsE%2Fv7%2FQdm%2Fj6ASbTo2M42Dt5Op3PC9DGw5qUBGbJosJ3olkrzGFGS1pdgG21G0TIIABiQVSC0DWsLW19tFt0rfI57PMGgvSwtIiE0MkVa%2BmNzf8TMkstm7Uh3p6YVtekL6PDIvORlkk4yuY%2B8Co8lGU6ER5zbc6zkrySLLgqJIakdZ4GMIws6%2FhBFg0OK6Prm5ZtsgT9d%2BM%2BDDr5vGSYURf0qtSDhjqDNxQ%2Foo0o4B7HDwXI2hFAnPtGrNOyJEVkuaPOsE6z64bmtHd09M4mlJv6obiM%2B%2Bjt%2B0SDZ1MEq8L3bZfjxVusaFhI%2FzRxNBBnrVAc0tEw7jr4FVl7QZqMZN1KEQ0xPPtDVIT8XViXLMYFMlotz1oc%2BOAWQlXENTccV65zTDdoL%2Bh07ZgB6TqImI1fs263%2BeftO5zai6I74lgUNTpPx34Yn4CwtKaB7XDM7bC8eqoabBZU0kquQTg4R6XCM2bQ6BypKhklG%2Fov8DDfSa5%2BAlVC%2FI8XCAAA">RemoveThenInsert.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VS2%2FTQBD%2BKyOLgy21Lg%2BJgyGVQhLUSC2gpkhImMPaHpMV69loH4EqqsSNKwce%2FwT%2BD7%2BE2bUTkjMHVCxLXs9%2B%2B83D34w3SZ0UyckJ%2FPr6%2BVbfJYUkvv2A8eXVfHI%2Bg9mr8cWL81kBbolQ6wahkbb21mIDkqJVGCdrhf3Rf53AX%2BdfUitJKKiVsBZeWjQFnAm7FJVC2JQEfK2FAdkUMCfXGyRJlw6WDDZgUbW5bGDEMLgJpAFlneBKQeuphtEIUrW0RfRwBGa7zOD4FJ5orba%2BwsXAyDYKOF71OzveSLjkGFNJTsdViFqS9i7GHmj36HpAXuuukoQcd7YjjJzhO375eKvvPonvn2A6u3gOZ%2BPLZ7PFogDSDlasV9BtlC5%2BEN1KYQ5zNpG6BuPJ7qQeSQBEpdescmpgZbjA%2Fb5B65XLYbIU9BZBOmgNIjMMTYGNdNrk%2F0kxS5LdSnPdnmpPDatYUzDGeqRlEgbGwoW6CgdlmU6Fw5z0%2B6xkVJIFqEIHnvXNLRFkHpvlXvbHzvJfoHsc9k4Z8zrY3pQUHn0j3d93OOEwXBFcxbMsZX7PoqstZMHl5xk1n9o9XCdWaVkyYZZbTgebNDs8FbrluBJhuimt3%2FnVgRNyQpKNr8O5EH4basIRHqJ4Cty5yy3b20Nv7SITHQuGeBpQjcPpioXj0MTKRpfRnA3FizP5J1yZ6wLqQXANcKsLFjS3MpDvKjSPQID1dY3Wtl4NCUCj0Ubhr4WS%2FO0w6rPzLjpjhSZHyZr%2FXg%2FzB8nNb4ZQYqDJBgAA">MutationLookup.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91WzU7bQBB%2BlZFPthQMtBUHl1BRCAIJSkXSqhJGaGNvyBZn1%2FKuQ1OE1FuvPfTnTdr36ZN0ZtdO4iBIqx4qalmJPTP7zczn2c%2B%2B9hIv8lZX4eeXTw%2F6jCU18fU7bJ%2F0DnYOO9B5s3308rATgRlySFTKIRU6KbXmKQhprawwIsm4W%2FqvG%2Fjr%2FmM5EJJlkGRMa3ileRHBPtND1s84XMcS8BizAkQawYE0ziCkMH5lCeAaNM8GoUihjWFwQ6AUpQ1DpmBQygTabfCzoY5shhYU9WUAK1vwXKmszkUHBlq0NsXhlfNMcS3gEGv0hTTKXlHVQqrS2NoJdg7OBYSJGvWF5Fh3MAW0mBZPD1VhDsWYpz1qXfu2sq4phLyY56HguswMVn%2FqfGfY9OlZVZgq4JzGZC0MN9fXGi1xAyX2i9HUtiVvPbjtR%2BAuN5sUs0XIZDubhdGtI%2FrRzFiVFLI85zL1LQx2Kw0TUtvbAJ5B7PViDyL834u9GQMOwJSFnOK8VUhT6mues4IZVdAasGtmdOESRlH3k2Wsl7iqe5qniyKqnk%2FJeSeVG0%2F%2BhEqXtGbDMRg0KWxw1eSCElt0zG1DcbznWF%2Bg7L3IfZev5aKDcMRyXGKNrRppobglD6eqZ9lzIPn5%2FOFBn66Jbx9ht3N0DPvbJy863W4EUhnAng2ogVVc%2Fo6NcqQNDtAkswkUpdRThbYgAKyvxijOMoUcx9A4vxvpEHaGTF5wEAYGBeeIUGk5TwUSG%2F4nZMZSjHKUMdhTpUxRfJUko%2BXDjz16z3UN8coMxLG%2FywwPpboKYoyisYrlXXtriTw1ZIliC55zRCeL78Sw3hjn0%2B3wOzqFo37PNqgbO5bcbayI2qpzB42YLun7SkYCP5UlDL4t%2B81lJ5XOza9Z1L6FRGzE8dVHUtgCcyUSHjX9V2JgYi%2Bkt9JrlpV8ia%2F6RPkBvWIS0eQDu8D0T%2BGS8xx%2FJiv4nu2LTJgJGK5x8CumOM66GtGYa5x8abikgWCZnf4xy%2FB5ZUpdlrnG%2Bfda3hg%2F6TbCx97NL1TSEbPeCQAA">SeedExperiment.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE92WzWrbQBDHX2XQSQJXISn0IOqAG7vEJR8lyqFQ9bCWRtEWedfsrp2GEOit1x768Sbt%2B%2FRJOrta2bKapoUWSmoMlmZnZvf%2Fk%2BaPr4M8SIKdHfj28f29%2FmbCivj0BUZn59ODowlMXoyOnx9NEjAVQi4LhILrfKk1FsCFizJleF5jU%2FqvBfyx%2FkyUXLAa8pppDaM8l0thEjhkumKzGuE6E0CfGg3wIoGpME1gxZRFs6jZ1QmbYwKpUVxc2IZ2mQtuQl8wuC0xajvbj8a6jHkBQ9qjF%2B2U0nLnrsm7aTfUhtFjgXIpchgOIawrnbRyBqA6dxE82IcnUtbdE1C6O8DQpsbtKdbdXduKmIRcGOmuUCWkUi6NY4VqS1CTEOdyPuMCCUS0bnjTZ56i1lyKH5lbxKw583TcQe%2FYbi%2FQ5g2udZhgba7vpuQP4Cn5u59RojLH6O8COp29xtxMCxSGlxxVaMVEPWh23j68vdffRsTndzCeHJ%2FC4ejsZJKmCQhpYEG%2BArJ0FoNv2HxRYwxTCon6CtRS6LUluSYAbCZX5EaigAUNlGnWFeplbWI4qJi4QOAGSoVIHbx5YcGNVPF%2FAjMTfL6QxO0pvegFvdpS2KDjEWaBNfbUWK7MQJaFY2YwFvIyyigriGyq9TU%2FJzQx3iGcce32bCsLnvG5q%2BrUuHkxj33dPrV46VdeZcJf9SzM9aGRqBeoTBY07RTWkhVY%2FPoM9KvdKVqRZ21pK6O0LBKrtz0kjZkwjAsdtvvQaG3062biaW8%2F%2B11z2fWCJb096u4U38cz8YmOiW4dxnUhND6wZVd7G00p0jTQw1q3JOOSChtVbSxu3HwLRmoZt3o2IDolHoSPRNvlJ3j5W9W3QNiL1kzdX4qvcK6uErjgNKPNYPYeExMN0ul4YBMEjfacVLuZveSmclW6BwJmWLEVdxMcDIIV%2FQt7FD8Mbr4DMgNGwZEJAAA%3D">IdentityModels.swift</a></li><li><a href="https://developer.apple.com/documentation/swift/hashable">Hashable: equal values hash the same essential components</a>.</li><li><a href="https://developer.apple.com/documentation/swift/objectidentifier">ObjectIdentifier: identity during an instance’s lifetime</a>.</li><li><a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/NativeSet.swift">Swift NativeSet lookup implementation</a>.</li><li><a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/HashTable.swift">Swift HashTable bucket mapping and table seeding</a>.</li><li><a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/Hasher.swift">Hasher: execution seed and persistence restrictions</a>.</li><li><a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/core/SipHash.swift">SipHash implementation and seed combination</a>.</li><li><a href="https://github.com/swiftlang/swift/blob/0b9e4c7c1eca15ba39d9a3dc87629b4835c09586/stdlib/public/stubs/GlobalObjects.cpp">Runtime initialization and deterministic hashing</a>.</li><li><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0206-hashable-enhancements.md">SE-0206: Hashable Enhancements</a>.</li><li><a href="https://developer.apple.com/documentation/xcode-release-notes/swift-4_2-release-notes-for-xcode-10">Apple’s Swift 4.2 release notes: randomized hashing and Hasher</a>.</li><li><a href="https://forums.swift.org/t/how-is-synthesized-hashable-implemented/15960/4">Karoy Lorentey on hashing in Swift 4.1 and 4.2</a>.</li><li><a href="https://developer.apple.com/documentation/swift/hasher">Hasher: do not persist hashes across executions</a>.</li><li><a href="https://developer.apple.com/documentation/cryptokit/sha256">SHA256 in CryptoKit</a>.</li></ul><p><em>Originally published at </em><a href="https://dementievmykola.com/blog/swift_set_mutable_keys/"><em>dementievmykola.com</em></a><em> on November 17, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8077afc08ad9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priority Inversion in Swift: Why DispatchSemaphore Is a Poor Lock]]></title>
            <link>https://medium.com/@mykola.dementiev/priority-inversion-in-swift-why-dispatchsemaphore-is-a-poor-lock-47647c72fe8d?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/47647c72fe8d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[dispatchsemaphore]]></category>
            <category><![CDATA[priority-inversion]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[locks]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 00:00:59 GMT</pubDate>
            <atom:updated>2026-11-09T17:42:22.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Why is DispatchSemaphore a bad <strong>lock</strong> when it comes to priority inversion?</p><p><strong>Because a semaphore has no concept of an owner.</strong> It manages a count of permits, and signal() may be called by any thread, not necessarily the one that called wait(). When a high-priority thread blocks in wait(), this mechanism does not tell the system which specific thread needs help to finish its work. For mutual exclusion, it is better to use a primitive with a known owner. Apple explicitly explains this difference between dispatch_semaphore and owner-aware locks in its <a href="https://developer.apple.com/videos/play/tech-talks/110147/">tech talk on CPU scheduling</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DPuH5aUYR_4F_WPg.jpg" /></figure><p><em>The rover on the cover is not a random choice: in 1997, priority inversion kept resetting the computer of the Mars Pathfinder lander that carried Sojourner to Mars. How that happened is explained </em><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/#what-happened-on-mars-pathfinder"><em>below</em></a><em>.</em></p><p>On an iPhone, this kind of dependency can show up as UI lag. On Mars Pathfinder, it led to resets of the lander’s computer. Three threads and one resource are enough to understand both cases.</p><h3>TL;DR</h3><ul><li>DispatchSemaphore has no owner. When <strong>High</strong> waits in wait(), the system does not know which thread to help, so <strong>Medium</strong> can keep preempting <strong>Low</strong> while <strong>High</strong> keeps waiting.</li><li>Priority inheritance works only when the owner is known. In Swift 6, Synchronization.Mutex on Darwin is built on os_unfair_lock, so the system can see who holds the <strong>lock</strong>.</li><li>On Mars Pathfinder in 1997, this kind of inversion kept resetting the lander’s computer. The team fixed it by enabling priority inheritance for the mutex.</li><li>The compiler does not check a semaphore used as a <strong>lock</strong>: with @unchecked Sendable you can forget wait() and silently lose data. Mutex does not let that code compile. You can run both versions right in the article.</li><li>Do not wait for a Task with a semaphore: it ties up a cooperative pool thread and can deadlock. Use await.</li></ul><h3>What priority inversion is</h3><p>Picture one <strong>CPU</strong> and three threads with fixed priorities: <strong>High &gt; Medium &gt; Low</strong>. The scheduler gives the <strong>CPU</strong> to the highest-priority thread that is ready to run. A thread waiting for a held <strong>lock</strong> is not ready: it cannot make progress without the resource.</p><ol><li><strong>Low</strong> takes the <strong>lock</strong> and starts modifying shared data.</li><li><strong>High</strong> wakes up, tries to take the same <strong>lock</strong>, and blocks.</li><li><strong>Medium</strong> becomes ready. It does not need this resource at all, but its priority is higher than <strong>Low</strong>’s, so it gets the <strong>CPU</strong>.</li><li><strong>Low</strong> does not finish its critical section, the <strong>lock</strong> stays held, and <strong>High</strong> keeps waiting.</li></ol><p>🔎 <strong>What to watch:</strong> keep your eye on the <strong>CPU</strong> row while it plays. While <strong>High</strong> waits for the <strong>lock</strong>, the <strong>CPU</strong> goes to <strong>Medium</strong>, not to <strong>Low</strong>, which holds the <strong>lock</strong>. The “<strong>High</strong> waits” counter shows how long the wait lasts, and “Caused by <strong>Medium</strong>” shows how much of it <strong>Medium</strong> takes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZX_usZjxt4_b-gf5" /></figure><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?diagramPlayer_state=play#diagram-priority-inversion">Play the animation on the site →</a></p><p>* Units are notional time units: one axis tick is one unit. This is a teaching scale, not milliseconds or a measurement of iOS performance. High waits from t=2 to t=8: 8 − 2 = 6 units; Medium’s work from t=2 to t=6 accounts for 6 − 2 = 4 of them.</p><p>* The lock row shows who owns the resource; the CPU row shows who is running. The bar color identifies the thread: High, Medium, or Low.</p><p><em>This is a teaching model of one </em><strong><em>CPU</em></strong><em> with fixed priorities. The steps on the time axis are notional; they do not show measurements or the exact behavior of the iOS scheduler.</em></p><p><strong>High</strong> depends on <strong>Low</strong> for as long as <strong>Low</strong> is modifying the shared data, and that part is unavoidable. A third participant makes the inversion worse: <strong>Medium extends High’s wait even though Medium has a lower priority than High and does not use the resource High needs</strong>.</p><p>This is called <em>unbounded priority inversion</em>: the delay is no longer limited to the rest of <strong>Low</strong>’s short critical section. That does not mean every call will necessarily hang forever. In the model above, any <strong>Medium</strong> work that becomes ready can postpone <strong>Low</strong>’s completion again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Teqd8J93ESD_VeE-.jpg" /></figure><p><em>Jim has to finish working on the file Michael is waiting for. Dwight occupies the only “</em><strong><em>CPU</em></strong><em>” with other work. In an office, this looks like an ordinary Monday; a scheduler needs a more precise description of the dependency.</em></p><p>A real iOS device has multiple cores, QoS classes, and a more complex scheduling policy. More cores do not remove the dependency on a held resource. Apple separately warns about priority inversions caused by QoS mismatches and the lack of automatic priority propagation when waiting on a semaphore in the <a href="https://developer.apple.com/documentation/xcode/diagnosing-performance-issues-early">Thread Performance Checker documentation</a>.</p><h3>How priority inheritance helps the owner</h3><p><strong>Priority inheritance</strong> means temporarily raising the effective priority of a <strong>lock</strong>’s owner while a higher-priority thread waits for that <strong>lock</strong>. In our model, <strong>Low</strong> gets the chance to finish its critical section before <strong>Medium</strong> runs. Once the <strong>lock</strong> is released, <strong>High</strong> can continue, and <strong>Low</strong> no longer needs the temporary boost.</p><p>🔎 <strong>What to watch:</strong> compare the <strong>CPU</strong> row with the previous diagram. Here <strong>Low</strong> gets a temporary boost and runs before <strong>Medium</strong>. <strong>Medium</strong> arrives at the same moment as in the previous diagram, but waits for the <strong>CPU</strong> (the striped bar in its row). So the “<strong>High</strong> waits” counter shows 2 units instead of 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*afsj7_34GUBE4W92" /></figure><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?diagramPlayer_state=play#diagram-priority-inheritance">Play the animation on the site →</a></p><p>* Units are notional time units: one axis tick is one unit. This is a teaching scale, not milliseconds or a measurement of iOS performance. High waits from t=2 to t=4: 4 − 2 = 2 units, instead of 6 in the diagram without priority inheritance.</p><p>* The lock row shows who owns the resource; the CPU row shows who is running. The bar color identifies the thread: High, Medium, or Low.</p><p><em>The amount of work is the same. What changed is the order: the owner can release the resource before </em><strong><em>Medium</em></strong><em>’s unrelated work gets the </em><strong><em>CPU</em></strong><em>.</em></p><p><strong>High</strong> does not take the <strong>lock</strong> away from <strong>Low</strong> and does not read half-modified data. The goal of the mechanism is to <strong>help the thread whose completion High depends on</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*awzjphXkHKtoP0Lo.jpg" /></figure><p><em>The file still belongs to Jim. A temporary boost lets him finish the work; after that, Michael gets the result.</em></p><h3>What actually happened on Mars Pathfinder</h3><p>Pathfinder <a href="https://science.nasa.gov/mission/mars-pathfinder/">landed in Ares Vallis on July 4, 1997</a>. The mission included a lander and the Sojourner rover. The priority inversion story concerns resets of the <strong>lander’s computer</strong>, not of the rover.</p><p>According to <a href="https://retis.santannapisa.it/~giorgio/mars/reeves.html">Glenn Reeves, who led the flight software team</a>, the high-priority task bc_dist distributed the data collected from the 1553 bus. The ASI/MET meteorological task ran at a lower priority. Their IPC used VxWorks pipe() and select(), which internally relied on a mutex protecting the wait list of file descriptors.</p><p>ASI/MET held that resource when tasks of medium priority preempted it. bc_dist blocked on the same mutex. It did not finish its work before the next cycle, the deadline check in bc_sched detected the failure, and the system reset the computer.</p><p>The team reproduced the problem on Earth and enabled priority inheritance by changing a global variable that sets the creation options of these mutexes. The change applied to every select() mutex created after the change, not only to the one used for bc_dist and ASI/MET: the initialization logic offered no easy way to target just that one. They verified the effect before sending the patch to the spacecraft. Reeves explicitly notes that the fix was delivered through a dedicated patching mechanism, <strong>not through the VxWorks shell</strong>.</p><p>The names are easy to mix up here: VxWorks calls this primitive a <em>mutual exclusion semaphore</em>. It has an owner; it is not the same thing as the counting DispatchSemaphore in Swift. The failure shows that even a mutex needs the right configuration and scheduling support for priority inheritance.</p><p>Early images of the lander, the ramps, and Sojourner are available in <a href="https://nssdc.gsfc.nasa.gov/planetary/marspath_images_h.html">NASA’s historical catalog</a>.</p><h3>Anti-pattern: DispatchSemaphore(value: 1) instead of a lock</h3><p>Here is a class that protects access to an array with a semaphore:</p><p>SemaphoreResource.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>import Dispatch<br> <br>final class SemaphoreResource: @unchecked Sendable {<br>    private let gate = DispatchSemaphore(value: 1)<br>    private var data: [String] = []<br> <br>    func append(_ value: String) {<br>        gate.wait()<br>        defer { gate.signal() }<br>        data.append(value)<br>    }<br> <br>    func snapshot() -&gt; [String] {<br>        gate.wait()<br>        defer { gate.signal() }<br>        return data<br>    }<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let resource = SemaphoreResource()<br>DispatchQueue.concurrentPerform(iterations: 1_000) { index in<br>    resource.append(&quot;value-\(index)&quot;)<br>}<br>let values = resource.snapshot()<br>print(&quot;Appended from 1,000 concurrent calls: \(values.count) values&quot;)<br>print(&quot;Every value is unique: \(Set(values).count == values.count)&quot;)<br> <br>// ▷ Try: add a method that reads `data` without gate.wait(). The compiler<br>//   stays silent: @unchecked Sendable switched that check off.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzWrbQBB%2BlUEnCRIlodCDIaUmcWkgadMoh0IUko00spZKu%2BrurBMTDLn12kN%2F3qR9nz5JZ1eyndDeciipEMbMz%2FfNDPONbqMiGkVbW%2FDr6%2Bcn%2FebKN%2FHtB4xPTg%2F2DicweT8%2BOj6cjIBqhEKXCKW0hbMWS5AqWIUhWTTYp%2F7rBh7df65k22lDsC9tJ6iovamSSjRQNMJayLAVXa0NnqDVzhQ4gpdOFTUWH3gmGapSXDUIt7kCfjojZ4IQGiSY%2Bj%2B7K%2BAVUDwTjWOYneRhzkwYKAWJEZxlZKSannP22bkvyIdVzAqi65gxvoABow9MlvT%2B8bTptZAUJ2tjiRUauO2dVk65vziBxb0AJk4H9IA9JC8e0FslOltrhobNF%2BsyH81ukJxRoYgVbWD2O%2Fbl7km%2FfRPfP8H%2B5OgtvB6fvJlk2QiUJuhYS6CrICu8EW3XYAoHbFLNHIxTdiXDAAIgrvSMFahKvzSKer9B6xpKYa8WaoogCSqDyAiDYLGUpE36nwxzJdhX2rH2SGrljWEecR75Y5aRn6sgyPN436%2Bc0tdJzlFR4kO9Ns0gZlbYHwL3m7sU7TuHDtNCq8IZg4qO0VTatLEkNIHbso4vtre3WYI87xJv%2BLdf4SXFUlV5FHS1yUWFwCSUs%2BjrCS7L1ayy1lJbNzcOSHx2KqNb2NlgXljXBoVoGq6HCXo4rtspSgbwQLdEmszQzHsHSAtOyY%2F%2BnHBqhjSkJ30%2B7O7CA7xhjOHL8RNOzXwEoixBQItU65J3TvgBi9LCpVf0JVxLdji6fxxSOA2r3XayQTOstyUxt2DZoujvZ9YyFBsHkuBmAVW83NFGNOOP8vP0WboTLX4DoXQ1KaIHAAA%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-semaphore-resource">Run this example on the site →</a></p><p>value: 1 lets one thread at a time into the critical section. The others wait. defer guarantees signal() when the method exits after a successful wait(). Both methods follow the same rule, so this implementation has no data race on its own.</p><p>The problem is in the primitive’s contract. <strong>Low</strong> called wait() and went inside. <strong>High</strong> now waits for a permit, but the semaphore does not require that <strong>Low</strong> be the one to call signal(). Such an API has no “this waiter depends on this owner” relationship. When a semaphore is used as a <strong>lock</strong>, the ownership rule exists only in the developer’s head.</p><p>🔎 <strong>What to watch:</strong> compare the two parts of the diagram. In the DispatchSemaphore part, the wait of <strong>High</strong> leads to no particular thread. In the “Mutex on Darwin” part, it leads to the owner <strong>Low</strong>, so the system knows whom to help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J2hddafL0XgSvl9B" /></figure><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?diagramPlayer_state=play#diagram-owner-dependency">Play the animation on the site →</a></p><p>@unchecked Sendable has a cost here too: the author of the class manually promises the compiler that all access to the mutable state is synchronized. If someone adds a method tomorrow that reads data without wait(), that promise becomes false. The attribute does not check the implementation for us.</p><h3>Synchronization.Mutex in Swift 6</h3><p>For short synchronous access to shared state, you can use Mutex. In the code below, the compiler checks the class’s Sendable conformance without @unchecked on our type:</p><p>MutexResource.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>import Synchronization<br> <br>final class MutexResource: Sendable {<br>    private let data = Mutex&lt;[String]&gt;([])<br> <br>    func append(_ value: String) {<br>        data.withLock { protectedData in<br>            protectedData.append(value)<br>        }<br>    }<br> <br>    func snapshot() -&gt; [String] {<br>        data.withLock { $0 }<br>    }<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Dispatch<br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let resource = MutexResource()<br>DispatchQueue.concurrentPerform(iterations: 1_000) { index in<br>    resource.append(&quot;value-\(index)&quot;)<br>}<br>let values = resource.snapshot()<br>print(&quot;Appended from 1,000 concurrent calls: \(values.count) values&quot;)<br>print(&quot;Every value is unique: \(Set(values).count == values.count)&quot;)<br> <br>// ▷ Try: add a method that reads the array without withLock. There is no<br>//   unprotected array to reach: it lives inside the Mutex.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzWrcMBB%2BlcH0YEPibCj0YJrAkmxpIGnTOIdCHIIizcaiXsmVRptsl4Xeeu2hP2%2FSvk%2BfpJJs7yaXXnooqfHBaGa%2B%2BWY832iZ8KRIdnbg19fPj%2FqtVCji2w8Yn50fHRxPYPJ2fHJ6PCmAagSuBYKQljtrUYBU8ZQZkrzBLvRfF%2FDX9VdKzlptCMqF4rXRSn5gJLUKlqlUrAHeMGvhxBHenaHVznAsoEQl2HWDsKwU%2BKc1cs4IoUECwYjBXhfx%2FKIkI9XN5X56cZkF0OA9dYoDa1sPkl7BnDUuQEbHbEAMT0DKbyXVx5q%2Fg6XPogk5oTgMKaTaeHYc7lnzHj6CZxvHVfe5ekDFKtbaWlOawfY%2BDJT%2FxOTJ6B5SBAvT8OXjo367Ir5%2FgsPJyWt4OT57NSnLApQmaP3Ug55GAeAdm7UN5nDkj1SzAOOUXQsmggCwaz33WlEijIaizm7QuoZyOKiZukGQBFOD6BF6aaGQpE3%2BnzRzLa1DaVtGvF4fvNDOy2eQWWxQWiVhD5UUGs0Iqir1Y4y50rdZ5b2SKJ4gL9OLcJDYIMrUewyZ3jh0mHOtuDMGFZ2imWozSyWhiXltAbtXo9HIy803X%2BDdWk0D%2FCCgKokS2vaEomMWqaw6LtFkPZN11EZKm8LGEclv0KnRM9jd8nlhww04axrPxyfo4DxvpyjrwWO6AWkyR7PoDCAtOCXfh9XhQ0ukPjzr4mFvDx7g9S2MC%2F8nnJtFAUwIYDBDqrXwA8hCc5mw%2FZo3bAFB8toRDNLP4bxGE5Mr3Y%2B6U%2BvN00eRDkC8LsKIN3LuWySVlf42Ccjxr%2FkhT7aSub9Gn%2BVP891k9Rvaek3eVAcAAA%3D%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-mutex-resource">Run this example on the site →</a></p><p>The array is stored <strong>inside the mutex</strong>. withLock provides exclusive access to it and releases the <strong>lock</strong> after the closure, including when the closure throws. snapshot() returns the array’s value, not a reference to an unprotected mutable object.</p><p>In <a href="https://github.com/swiftlang/swift/blob/swift-6.0-RELEASE/stdlib/public/Synchronization/Mutex/DarwinImpl.swift">Swift 6.0’s Darwin implementation</a>, Mutex is built on os_unfair_lock. Apple <a href="https://developer.apple.com/documentation/os/os_unfair_lock_lock">documents the owner-thread information</a> that the system may use to try to resolve priority inversion. That ownership information is what the system needs to help <strong>Low</strong>.</p><p>A withLock call does not have to enter the kernel every time. The API also does not promise that <strong>High</strong> runs immediately or in FIFO order, and it does not protect you from long work done while holding the <strong>lock</strong>. In <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0433-mutex.md">SE-0433</a>, the guarantee is stated as mutual exclusion; specific scheduling properties depend on the platform.</p><p>The example targets <strong>Swift 6 and iOS 18+ / macOS 15+</strong>. The compiler version and the minimum OS version are separate requirements: installing a new Xcode does not by itself make the API available on an older OS.</p><h3>Forget the lock and see what happens</h3><p>The promise behind @unchecked Sendable is easy to break. On the left, a semaphore-based counter whose increment() forgets gate.wait(). The compiler stays silent. On the right, the same counter built on Mutex: the value lives inside the mutex, so the only way to change it is withLock, and value += 1 outside it does not compile. Press “Run both”: on the left some increments get lost, on the right the count is exactly 1,000,000.</p><p><strong>With the bug</strong></p><p>CounterSemaphore.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>import Dispatch<br> <br>final class Counter: @unchecked Sendable {<br>    private let gate = DispatchSemaphore(value: 1)<br>    private var value = 0<br> <br>    func increment() {<br>        value += 1 // Bug: no gate.wait()<br>    }<br> <br>    func read() -&gt; Int {<br>        gate.wait()<br>        defer { gate.signal() }<br>        return value<br>    }<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1_000_000) { _ in<br>    counter.increment()<br>}<br>print(&quot;Counted \(counter.read()) of 1000000 increments&quot;)<br> <br>// ▷ Try: add gate.wait() and defer { gate.signal() } to increment().<br>//   The count becomes exact, but only because you remembered.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE92VzYrbMBDHX2XwyaFbb0KhB8OWpklKA7vtdpNDD4ZFkcaJqC0ZfWQbQqC3vfbQjzdp36dP0pHsZLOUnnooWyGDGc2HNP7%2F5G3Ckzw5PYWfXz496FmocIiv32F4NZ%2BOzicweTe8uDyf5OBWCFwLBCEt99aiAKmilRkneYVt6L8%2BwF%2Bfv1CybrRxMJa2YY6vgqmUilXAK2YtjLRXDk0Oz73iK%2BTvqRMzVIItKoRtoYBGY%2BSaOYQKHSzDy9kh3Qxr1qy0wXTNKo85DHr3Y9bMQFyioH4oHhZLqkX95gZrVC7t7QuF0To%2FOoMB0Bd44Zc5KB3LZjdMknPruruXyyATlObxM5gqd5ztt7gwBJZoYNsuWrmkblDw7s7BoPNGtVs5lIsVgyg%2Bf3zQsz3Et1sYTy7ewKvh1evJbBaa7KAh8YMuIwf4gdVNhRlMyaSqDRiv7IGbmASALfSakFEifG%2Fl2nWD1lcug9GKqSWCdFAaRMrQEYZCOm2y%2F6SZB8JeEkmCOalVMMZ%2BpEUSbp%2BZC31lDooiHQfNKX3TK8gr6QXXgBVvMSRIOiCDXveQvfXoMeNacW8MAXOJptSmTiX5xYKWuLvu9%2FvhIZjgmlrd6rbLmx3BFpW8315bTYSd7V1blnpBB4N%2BHHeo2m7L8Vr9AXOzyYEJcYxZVMMfCAOnj7HPOhXNo6ioOiyQ6xptEB93J7DwnfbIzrxF2GgPIbpeoEFB8clJsqZ%2F1dPsSTZIdr8ASba1grkGAAA%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-counter-semaphore">Run this example on the site →</a></p><p><strong>Fixed</strong></p><p>CounterMutex.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>import Synchronization<br> <br>final class Counter: Sendable {<br>    private let value = Mutex(0)<br> <br>    func increment() {<br>        value.withLock { $0 += 1 }<br>    }<br> <br>    func read() -&gt; Int {<br>        value.withLock { $0 }<br>    }<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let counter = Counter()<br>DispatchQueue.concurrentPerform(iterations: 1_000_000) { _ in<br>    counter.increment()<br>}<br>print(&quot;Counted \(counter.read()) of 1000000 increments&quot;)<br> <br>// ▷ Try: write value += 1 without withLock. The compiler rejects it,<br>//   so the lock cannot be forgotten.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE92VzY7TMBDHX2UUcUjFkk2FxCHSIlVtEZVaWLY9cIi0cp3p1pCOK2fSbqkqcePKgY83gffhSRg7aRdOHDigxXIu9sx4Zvz7O%2FtIR1l0fg4%2FPn%2B81zMnX8SXb9C7mo364yEMX%2Fcml%2BNhBrxE0LZAKEyl66rCAgyFVeXY6BIb139dwF%2FXn5NZra1jmO5IL50l806xseR3FoZUCbpUVQV9WxOjy2CKVKh5ibDPCWSsndkoRiiRYaPKGuECJjXjbZx2fBBvs6hJS%2Fu0wxUSx52jrx%2FBJ9kaXo6tfgt7eJDCwwvowqGxOfwWxKEqxP%2FRUxgR%2FynMXYQQxN%2FXp%2Ff3ejZFfP0Ag%2BHkJTzvXb0YTqcZkGVYC5dgFwFRvFWrdYkJjGSJyh24mqoT0iEIgJrbjdBMhb9C4mbfYVWXnEB%2FqegGwTAsHKJEaOHHwrB1yX%2FSzBP8z4Tu4sR96EecR%2F5hmLLvq2LI83ggnCdkt51crKJAt6deN9IQ7luRxLI1MNVasV6%2BqlG41JZ07ZzAf4luYd0qNmIXDqwy6F6naeo%2FEQZcS6sbbtu4yS%2FCCSQf02tOK3xmR9NGHh3PQTcN4052VZtyePG%2Bw8ztMtg6yaOVbRCdF5CtGY5CSmAWqFmtTSklOnyDWlAxfNZSVNnARelFpxV5EucIUuKNZUYSUqKzaCN%2FiyfJ46QbHX4C8r6QtjsGAAA%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-counter-mutex">Run this example on the site →</a></p><p>What changed</p><p>CounterSemaphore.swift → CounterMutex.swift</p><pre>-import Dispatch<br>+import Synchronization<br> <br>-final class Counter: @unchecked Sendable {<br>-    private let gate = DispatchSemaphore(value: 1)<br>-    private var value = 0<br>+final class Counter: Sendable {<br>+    private let value = Mutex(0)<br> <br>     func increment() {<br>-        value += 1 // Bug: no gate.wait()<br>+        value.withLock { $0 += 1 }<br>     }<br> <br>     func read() -&gt; Int {<br>-        gate.wait()<br>-        defer { gate.signal() }<br>-        return value<br>+        value.withLock { $0 }<br>     }<br> }</pre><p>The playground cannot show priority inversion itself. We checked: on its Linux server, <strong>High</strong> waited just as long with a semaphore as with Mutex. So the diagrams above explain the inversion, and this example shows another cost of using a semaphore as a <strong>lock</strong>: the compiler does not check that every access to the state goes through wait().</p><h3>What belongs in a critical section</h3><p>When the <strong>lock</strong> is contended, Mutex blocks the calling thread, and it is not recursive. Inside withLock, we keep a short operation on the state. We do not make a network request, perform disk I/O, wait for another task, or call an arbitrary callback. Calling withLock on the same mutex from inside its own critical section is a bug: the behavior is platform-dependent, and some platforms may crash the process or deadlock.</p><p>The withLock closure is synchronous, so you cannot await inside it. Take the snapshot of the state you need, release the <strong>lock</strong>, and only then do the asynchronous work. If you need to apply the result after await, the state may have changed in the meantime, so check the relevant conditions again.</p><h3>A semaphore inside a Task sets another trap</h3><p>It is tempting to wrap an async operation in a Task and wait for its result synchronously with a semaphore. If that wait runs on a thread from the cooperative pool, it occupies the thread, while the work that has to call signal() may need a thread from the same pool. Under enough load, this can cause a deadlock.</p><p>On the left is this anti-pattern. The program starts as many tasks as it sees cores, and each one waits for an inner Task with a semaphore. No thread is left to run the inner tasks, so the program hangs until the playground stops it after 10 seconds. On the right, currentValue() becomes async and waits with await: the task suspends and frees its thread.</p><p><strong>With the bug</strong></p><p>TaskSemaphore.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>import Dispatch<br> <br>func loadValue() async -&gt; Int { 42 }<br> <br>final class Box: @unchecked Sendable {<br>    var value = 0<br>}<br> <br>// Waits for async work on a blocked thread.<br>func currentValue() -&gt; Int {<br>    let done = DispatchSemaphore(value: 0)<br>    let box = Box()<br>    Task {<br>        box.value = await loadValue()<br>        done.signal()<br>    }<br>    done.wait() // Bug: blocks a pool thread<br>    return box.value<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let workers = ProcessInfo.processInfo.activeProcessorCount<br>print(&quot;Starting \(workers) tasks, one per core&quot;)<br>let total = await withTaskGroup(of: Int.self) { group in<br>    for _ in 0..&lt;workers {<br>        group.addTask { currentValue() }<br>    }<br>    var sum = 0<br>    for await value in group { sum += value }<br>    return sum<br>}<br>print(&quot;All tasks finished, sum: \(total)&quot;)<br> <br>// ▷ Try: start workers - 1 tasks. A free pool thread runs the inner<br>//   Task and the program finishes, which is how this bug hides in tests.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzW7UMBB%2BlVFOG1HcFhCHiCK27QIrtVB1K%2BAQCXmTycaq145sZ7fVaiVuXDnw8ybwPn0SxnbS3XLlgEqUKNF4PN98M%2F4mq6RIsmR3F26%2BfbnXd648ie8%2FYXh%2BMT46GcHow%2FD07GSUgasRCl0ilMIWrbVYglDByo0ThcS49V8T%2BGv%2BuRLzRhsHx8I23BW1N1WtKkBqXr7jssVBCtxek%2BXhcxgrByt48gjWwU8oLqGQ3Fo41FcZvKCNNRaXVK0JqpJPJcIqV0DXght6KBwcwF6uwn6q4HsunIVKmw5jqc0laAUcplKHQK42yEvWZVW0xqByfWJ9ShFDooNSKw%2FR05ngnDe1NjgI4BnspRvfqb4iV8p80BkvuL3sg%2FmLHFifNF9SqttV2bh5TGbFjKrRm9fxFVb8RsqV2B62sywSs8Sw0Vp29KK3QdcatUHdlOnm66d7fUcSPz7D8ej0Lbwenr8ZTSYZKO2gIUGBroK28IrPG4kMxmRS8hpMq%2BytFkMQAD7VC5KhKqExQrm4btC20jE4qrmaIVCnKoNIETrVYimcNuw%2FKeatal%2FqlmTmhFbeGOoxyBM%2F0SbO15U7yPPBMXfIlF6mOXklqXf1x99rDY2ls31mdIHWjlWlWbP1zQsnFtitanNEaG4DEyCEmnmILlYKjiRkd8CrsEFDfTMYID2g047mRS%2BlpXC1F9wro9tmoKvMS5lZlFVKM2bmrdS9qAw%2FID76Xu4x9qzPe0uowZvxsowK%2FnNMrO%2BI0o8i287jIOqjx5yi2Aknwq%2BC34ODzr6%2BI1NaCgLtyzGUMrIHmovC1ljueJ%2FMlycwT7vah3%2FOL7gw1xnY0Kae0UPYjyEYDMMB3p4RGzEIpdB0agiEvRj8AvVuZvi8T4D6sKxFUYOwUOsludDHtJ1BLUq0QRponSVVJDvJgn7pT9ljtp%2BsfwMYXxQt4AcAAA%3D%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-task-semaphore">Run this example on the site →</a></p><p><strong>Fixed</strong></p><p>TaskAwait.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>func loadValue() async -&gt; Int { 42 }<br> <br>// Suspends the task and frees its thread.<br>func currentValue() async -&gt; Int {<br>    await loadValue()<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>let workers = ProcessInfo.processInfo.activeProcessorCount<br>print(&quot;Starting \(workers) tasks, one per core&quot;)<br>let total = await withTaskGroup(of: Int.self) { group in<br>    for _ in 0..&lt;workers {<br>        group.addTask { await currentValue() }<br>    }<br>    var sum = 0<br>    for await value in group { sum += value }<br>    return sum<br>}<br>print(&quot;All tasks finished, sum: \(total)&quot;)<br> <br>// ▷ Try: start 100 tasks instead of workers. They suspend rather than<br>//   block, so the program still finishes.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzW7TQBB%2BlZFPsQjbFBAHiyJFaYBILVRNhDhYQlt7nKzizFq764QoitQbVw78vAm8T5%2BE2fWGVogbB1QsS4lmZ%2Bab%2BWa%2B9S4pkiw5OoKbL5%2Fu9ZuTb%2BLrdxheziajszGM3w3PL87GGbgFQqFLhFLZorUWS1AUrNI4VdTYhf7rBv66%2F5yqlgqotSzfyrrFXgrSbtny8DlMyMEOnjyCvffjdqetbZBKG3hw0i5BUgmVQbSgnDcblKWIOYvWGCT357Q5AT9yI5W7C57TAevm8%2FW9frsmvn2E0%2FH5G3g1vHw9nk4zIO2g4RUCXQUW8YNcNTUKmLCJ6i2Yluyv7QtJmKYrvcbAdWMUue7coG1rJ2C0kDRH5j8MgjPEPcVSOW3Ef0JmTmrVaObthW6plE5p8sbARy9PvIanzvMqHeR571Q6FKQ3ac5eSepda3Sw0WaJxsIJXBhdoLUTqrRo7vyXhVNrjKfajBjN3cIECEVzDxFzpUEIts%2FTQ2jQ8NwMBkgP6LSTNcN1i75RbjFj75dGt01PV5nXgrBYVykLbe6tPL1OGpU28N7PciDEs0PdUTb%2BCd5ClqVPyNEdwm%2Ba23f%2B8WctDdh2xeUMbjG6uLUP8GhdEbvg9%2BAk2mO8Qdca8kdBpgdShnXdcQCVImUXWPa9T%2BZJCv2ncQLhrv0BM7PNwIZhHQ8GMVSRdXx3eFnEZgXMFrjlTOHOASN5qQ1vtqSoiqtaF0uG0mHdeYhzI1ecWHE9sRLL65%2F0kzV%2FrZ6Kx%2BI42f8ETATCc7sGAAA%3D">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-task-await">Run this example on the site →</a></p><p>What changed</p><p>TaskSemaphore.swift → TaskAwait.swift</p><pre>-import Dispatch<br>-<br> func loadValue() async -&gt; Int { 42 }<br> <br>-final class Box: @unchecked Sendable {<br>-    var value = 0<br>-}<br>-<br>-// Waits for async work on a blocked thread.<br>-func currentValue() -&gt; Int {<br>-    let done = DispatchSemaphore(value: 0)<br>-    let box = Box()<br>-    Task {<br>-        box.value = await loadValue()<br>-        done.signal()<br>-    }<br>-    done.wait() // Bug: blocks a pool thread<br>-    return box.value<br>+// Suspends the task and frees its thread.<br>+func currentValue() async -&gt; Int {<br>+    await loadValue()<br> }</pre><p>Apple explains the forward-progress contract and the danger of hidden dependencies in <a href="https://developer.apple.com/videos/play/wwdc2021/10254/">Swift concurrency: Behind the scenes</a>. To wait for an async result, use await; to adapt a callback API, use a continuation and resume it exactly once.</p><p>When the state belongs to an asynchronous component, consider an actor. Waiting for access to an actor can suspend the task and free the thread for other work. At the same time, when an actor method suspends at an await, the actor can run other calls in the meantime, so re-check any assumption about its state after each suspension point. This model is described in <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/">The Swift Programming Language</a>.</p><h3>What the example verifies</h3><p>The <a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/resource-examples.zip">archive with the complete Swift files</a> contains both implementations and a verification program. It adds 10,000 unique values from concurrent calls, reads snapshots while writes are in progress, and checks the final set of values.</p><p>You can run the verification program right here. It runs on an online playground with a Linux toolchain, so it checks the same data integrity, not the Darwin scheduler.</p><p>main.swift</p><pre>// ════════════════════════════════════════════════════════════════<br>// ▶ ARTICLE EXAMPLE: the code discussed in the article<br>// ════════════════════════════════════════════════════════════════<br> <br>import Dispatch<br> <br>// Adds unique values from concurrent workers, reads snapshots while they<br>// are still writing, and checks that both resources kept every value.<br>func verifyResources(iterations: Int = 10_000) {<br>    let semaphoreResource = SemaphoreResource()<br>    let mutexResource = MutexResource()<br> <br>    DispatchQueue.concurrentPerform(iterations: iterations) { index in<br>        let value = String(index)<br>        semaphoreResource.append(value)<br>        mutexResource.append(value)<br> <br>        // Exercise reads while other workers are still writing.<br>        if index.isMultiple(of: 997) {<br>            precondition(semaphoreResource.snapshot().count &lt;= iterations)<br>            precondition(mutexResource.snapshot().count &lt;= iterations)<br>        }<br>    }<br> <br>    let expected = Set((0..&lt;iterations).map(String.init))<br>    let semaphoreValues = semaphoreResource.snapshot()<br>    let mutexValues = mutexResource.snapshot()<br>    precondition(semaphoreValues.count == iterations)<br>    precondition(mutexValues.count == iterations)<br>    precondition(Set(semaphoreValues) == expected)<br>    precondition(Set(mutexValues) == expected)<br>    print(&quot;Both resources retained all \(iterations) unique values.&quot;)<br>    print(&quot;This checks data integrity, not scheduling or priority inheritance.&quot;)<br>}<br> <br>// ────────────────────────────────────────────────────────────────<br>// ◇ DEMO HARNESS: not part of the example. It only runs the code<br>//   above and prints the result. Change it freely in the editor.<br>// ────────────────────────────────────────────────────────────────<br> <br>import Foundation<br> <br>print(&quot;▶ Start at \(Date.now)\n&quot;)<br> <br>verifyResources()<br> <br>// ▷ Try: call verifyResources(iterations: 100_000). It still passes: both<br>//   classes guard every access, so this checks integrity, not scheduling.</pre><p><a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91X224bNxD9lYFQoLuAspFRoEUEK6gaqagBO00toyhgGQG1O9ISXpFbkqtLDQN962sfkvRPmv%2FJl3RI7k0XG037lMh6sMm5npk5Q9914k6%2Fw5e5VAZGXOfMxOlUlAeTrYhTJQX%2FjRkuRX3%2BvSxEUh5NxdOnMMKMz1Axg9kWCo0aGGhcsjyVCoHZPzMZ38JcKjApnSjD4wy%2F1BDLZc4U11JEztIwy4DFMWoNXIOuA8CkC7PCOO3GckqmhQS5FlwsnphUIUvIpDCKxYYMzrlgGcQZI3OTSusStSxUjH34tiDzGN9iQreU0SxDuJsKoE%2Bu%2BIrSgQwNLOwvgxqe2lCwYllBZk7CXZ0VU0DwsD5cT4yiyG5I%2B%2FrGYmXF5uQVWJ6Tx%2BA1lDa8YFi5tx%2FrNlozboKwOUxwjgru%2FKXmC8ovCOG%2BJUCOo9K6s10q3%2B%2B414LlOpVkGp48b8L8394VmkIJF0Tt1nluV%2BKiMLhpqvAY9NYQgec0TqswnwfXN%2BHHoulwWXOTnttGvCMv0mBsMBlZF1w0kj6G1u0xOMvc%2Fguy%2B5F80WtZui8n6sPbPz%2Fpr0%2Fi3d8wvLw6e3E%2BhvEvw4tX5%2BO%2Bm%2BBYJggJ13GhNQ0fF21W%2BEzyLws5TBINheC%2FFui7U8NcyaVlqbhQCoWBtVS3qHQXLH3puoM0rFNOY0HQbJ0pRoynDSeGXCtuqK26wATxnaUwTWLMwEyalMz40dJwi7kBXKHaet%2BWEm2T0gmfb6sR1AE3lryJz3UfziiiAZz0Xvd6vXqC7CzqfQIlsQNSrdjCKizbc15NcVvQi1a8%2BlOBFGGDyytUtC%2BWO8E1v1No1DcJbnZm17p1mdrY3OgFTqg1tQdpPDTeO%2BHvCzViVJjxBlXMNZYF9GWjShBXlrU9rF3UWOBzn0nE9UWRGZ5nGMh5H549%2B2aHwjwxISGUcItBcJhKwz4EZEGVPB20MXvE1m62%2F9rOPgfaAuAmd9zp%2BsMEQS%2BKTlvKEQUd%2BOJEXHAThkd67Gc%2FKoMj5Wpi22u1WuehXKr9cgxCr1xmOziS7SFaH6diodjzFlqtCq2HdFqujstzYYJp57vdyadFzLigGjBquek0aA%2FODhtF086epauUXl4lqSR%2BORpcUNduu%2FTYohrRXVJkVD6g5xxpSXtHUtTv3DBBkDub9Sp78%2Fsn%2FfVJ%2FPUHjMYXP8IPw8uX48mk76Cgp6sBOXfbCzdsSZMbwRkdCXoHq0Loets5IwBsJlfoWNuh7e%2BpajT2EbxImVggtRFtCLQv6XIvInWDVNFnAqb9qVrNPhAmxoJIu4u6dGTflUKuwylJdRzN7q%2BqsOqqd%2B%2FhSm37ENsOf2yhnfT8LnOV8Ryc0zMU6cquy7Iy7mlKg7MomErKnen%2FEemCllSHZigenAcqUafbWdF%2FVF9HX0Unnft%2FADmMjadfDQAA">Open in the online editor</a></p><p><a href="https://dementievmykola.com/blog/priority_inversion_semaphore_mutex/?runnableCode_state=run#runnable-resource-check">Run this example on the site →</a></p><p>To build it locally:</p><pre>swiftc -swift-version 6 -strict-concurrency=complete -warnings-as-errors \<br>  Resources.swift main.swift -o resource-check<br>./resource-check</pre><pre>▶ Start at 2026-11-09 11:43:06 +0000<br> <br>Both resources retained all 10000 unique values.<br>This checks data integrity, not scheduling or priority inheritance.</pre><p>The example was compiled with Apple Swift 6.4.2 in Swift 6 mode, and the check was run on macOS. The code was also type-checked separately for iOS 18. This verifies the correctness of data access; it is <strong>not a benchmark and not proof of a scheduler policy</strong>. A random order of print() calls or an artificial sleep() would not prove priority inheritance either.</p><p>When you see this in an app, start with the <a href="https://developer.apple.com/documentation/xcode/diagnosing-performance-issues-early">Thread Performance Checker</a>: find out who is waiting, what exactly they are waiting for, and whose progress would unblock them. Then check how long the critical section takes and the priorities of the work. A .background QoS class on its own does not explain the dependency.</p><h3>How to choose a primitive</h3><ul><li><strong>Briefly modify shared state synchronously</strong>: Mutex, if the deployment target allows it</li><li><strong>Own the state of an asynchronous component</strong>: actor, keeping reentrancy in mind</li><li><strong>Wait for an async operation to finish</strong>: await, without blocking a thread on a semaphore</li><li><strong>Count permits that another thread or task may return</strong>: A semaphore may fit the model; evaluate blocking and dependencies separately</li></ul><p>For mutual exclusion, information about the resource’s owner matters. It lets the system help the thread that urgent work depends on. In Swift, Mutex also adds a useful boundary in the code: the state lives inside the protecting primitive, and access to it goes through withLock.</p><p>Priority inheritance does not shorten a long critical section and does not fix wrong dependencies. Choose the right primitive, keep only short work under the <strong>lock</strong>, and let async code wait without occupying a thread. These are the decisions that determine how long <strong>High</strong> actually waits.</p><h3>Additional resources</h3><ul><li><a href="https://science.nasa.gov/mission/mars-pathfinder/">NASA: Mars Pathfinder, mission overview</a></li><li><a href="https://nssdc.gsfc.nasa.gov/planetary/marspath_images_h.html">NASA NSSDCA: historical Mars Pathfinder images</a></li><li><a href="https://retis.santannapisa.it/~giorgio/mars/reeves.html">Glenn Reeves: “What Really Happened on Mars?” (December 15, 1997)</a></li><li><a href="https://developer.apple.com/videos/play/tech-talks/110147/">Apple: Tune CPU job scheduling for Apple silicon games (owner-aware primitives)</a></li><li><a href="https://developer.apple.com/documentation/xcode/diagnosing-performance-issues-early">Apple: Diagnosing performance issues early (Thread Performance Checker)</a></li><li><a href="https://developer.apple.com/documentation/os/os_unfair_lock_lock">Apple: os_unfair_lock_lock (owner and fairness limits)</a></li><li><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0433-mutex.md">Swift Evolution SE-0433: Synchronous Mutual Exclusion Lock</a></li><li><a href="https://github.com/swiftlang/swift/blob/swift-6.0-RELEASE/stdlib/public/Synchronization/Mutex/Mutex.swift">Swift 6.0: Mutex source code</a></li><li><a href="https://github.com/swiftlang/swift/blob/swift-6.0-RELEASE/stdlib/public/Synchronization/Mutex/DarwinImpl.swift">Swift 6.0: DarwinImpl.swift</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2021/10254/">Apple WWDC21: Swift concurrency: Behind the scenes</a></li><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/">The Swift Programming Language: Concurrency</a></li><li>Code examples in the online editor: <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzWrbQBB%2BlUEnCRIlodCDIaUmcWkgadMoh0IUko00spZKu%2BrurBMTDLn12kN%2F3qR9nz5JZ1eyndDeciipEMbMz%2FfNDPONbqMiGkVbW%2FDr6%2Bcn%2FebKN%2FHtB4xPTg%2F2DicweT8%2BOj6cjIBqhEKXCKW0hbMWS5AqWIUhWTTYp%2F7rBh7df65k22lDsC9tJ6iovamSSjRQNMJayLAVXa0NnqDVzhQ4gpdOFTUWH3gmGapSXDUIt7kCfjojZ4IQGiSY%2Bj%2B7K%2BAVUDwTjWOYneRhzkwYKAWJEZxlZKSannP22bkvyIdVzAqi65gxvoABow9MlvT%2B8bTptZAUJ2tjiRUauO2dVk65vziBxb0AJk4H9IA9JC8e0FslOltrhobNF%2BsyH81ukJxRoYgVbWD2O%2Fbl7km%2FfRPfP8H%2B5OgtvB6fvJlk2QiUJuhYS6CrICu8EW3XYAoHbFLNHIxTdiXDAAIgrvSMFahKvzSKer9B6xpKYa8WaoogCSqDyAiDYLGUpE36nwxzJdhX2rH2SGrljWEecR75Y5aRn6sgyPN436%2Bc0tdJzlFR4kO9Ns0gZlbYHwL3m7sU7TuHDtNCq8IZg4qO0VTatLEkNIHbso4vtre3WYI87xJv%2BLdf4SXFUlV5FHS1yUWFwCSUs%2BjrCS7L1ayy1lJbNzcOSHx2KqNb2NlgXljXBoVoGq6HCXo4rtspSgbwQLdEmszQzHsHSAtOyY%2F%2BnHBqhjSkJ30%2B7O7CA7xhjOHL8RNOzXwEoixBQItU65J3TvgBi9LCpVf0JVxLdji6fxxSOA2r3XayQTOstyUxt2DZoujvZ9YyFBsHkuBmAVW83NFGNOOP8vP0WboTLX4DoXQ1KaIHAAA%3D">SemaphoreResource.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzWrcMBB%2BlcH0YEPibCj0YJrAkmxpIGnTOIdCHIIizcaiXsmVRptsl4Xeeu2hP2%2FSvk%2BfpJJs7yaXXnooqfHBaGa%2B%2BWY832iZ8KRIdnbg19fPj%2FqtVCji2w8Yn50fHRxPYPJ2fHJ6PCmAagSuBYKQljtrUYBU8ZQZkrzBLvRfF%2FDX9VdKzlptCMqF4rXRSn5gJLUKlqlUrAHeMGvhxBHenaHVznAsoEQl2HWDsKwU%2BKc1cs4IoUECwYjBXhfx%2FKIkI9XN5X56cZkF0OA9dYoDa1sPkl7BnDUuQEbHbEAMT0DKbyXVx5q%2Fg6XPogk5oTgMKaTaeHYc7lnzHj6CZxvHVfe5ekDFKtbaWlOawfY%2BDJT%2FxOTJ6B5SBAvT8OXjo367Ir5%2FgsPJyWt4OT57NSnLApQmaP3Ug55GAeAdm7UN5nDkj1SzAOOUXQsmggCwaz33WlEijIaizm7QuoZyOKiZukGQBFOD6BF6aaGQpE3%2BnzRzLa1DaVtGvF4fvNDOy2eQWWxQWiVhD5UUGs0Iqir1Y4y50rdZ5b2SKJ4gL9OLcJDYIMrUewyZ3jh0mHOtuDMGFZ2imWozSyWhiXltAbtXo9HIy803X%2BDdWk0D%2FCCgKokS2vaEomMWqaw6LtFkPZN11EZKm8LGEclv0KnRM9jd8nlhww04axrPxyfo4DxvpyjrwWO6AWkyR7PoDCAtOCXfh9XhQ0ukPjzr4mFvDx7g9S2MC%2F8nnJtFAUwIYDBDqrXwA8hCc5mw%2FZo3bAFB8toRDNLP4bxGE5Mr3Y%2B6U%2BvN00eRDkC8LsKIN3LuWySVlf42Ccjxr%2FkhT7aSub9Gn%2BVP891k9Rvaek3eVAcAAA%3D%3D">MutexResource.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE92VzYrbMBDHX2XwyaFbb0KhB8OWpklKA7vtdpNDD4ZFkcaJqC0ZfWQbQqC3vfbQjzdp36dP0pHsZLOUnnooWyGDGc2HNP7%2F5G3Ckzw5PYWfXz496FmocIiv32F4NZ%2BOzicweTe8uDyf5OBWCFwLBCEt99aiAKmilRkneYVt6L8%2BwF%2Bfv1CybrRxMJa2YY6vgqmUilXAK2YtjLRXDk0Oz73iK%2BTvqRMzVIItKoRtoYBGY%2BSaOYQKHSzDy9kh3Qxr1qy0wXTNKo85DHr3Y9bMQFyioH4oHhZLqkX95gZrVC7t7QuF0To%2FOoMB0Bd44Zc5KB3LZjdMknPruruXyyATlObxM5gqd5ztt7gwBJZoYNsuWrmkblDw7s7BoPNGtVs5lIsVgyg%2Bf3zQsz3Et1sYTy7ewKvh1evJbBaa7KAh8YMuIwf4gdVNhRlMyaSqDRiv7IGbmASALfSakFEifG%2Fl2nWD1lcug9GKqSWCdFAaRMrQEYZCOm2y%2F6SZB8JeEkmCOalVMMZ%2BpEUSbp%2BZC31lDooiHQfNKX3TK8gr6QXXgBVvMSRIOiCDXveQvfXoMeNacW8MAXOJptSmTiX5xYKWuLvu9%2FvhIZjgmlrd6rbLmx3BFpW8315bTYSd7V1blnpBB4N%2BHHeo2m7L8Vr9AXOzyYEJcYxZVMMfCAOnj7HPOhXNo6ioOiyQ6xptEB93J7DwnfbIzrxF2GgPIbpeoEFB8clJsqZ%2F1dPsSTZIdr8ASba1grkGAAA%3D">CounterSemaphore.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE92VzY7TMBDHX2UUcUjFkk2FxCHSIlVtEZVaWLY9cIi0cp3p1pCOK2fSbqkqcePKgY83gffhSRg7aRdOHDigxXIu9sx4Zvz7O%2FtIR1l0fg4%2FPn%2B81zMnX8SXb9C7mo364yEMX%2Fcml%2BNhBrxE0LZAKEyl66rCAgyFVeXY6BIb139dwF%2FXn5NZra1jmO5IL50l806xseR3FoZUCbpUVQV9WxOjy2CKVKh5ibDPCWSsndkoRiiRYaPKGuECJjXjbZx2fBBvs6hJS%2Fu0wxUSx52jrx%2FBJ9kaXo6tfgt7eJDCwwvowqGxOfwWxKEqxP%2FRUxgR%2FynMXYQQxN%2FXp%2Ff3ejZFfP0Ag%2BHkJTzvXb0YTqcZkGVYC5dgFwFRvFWrdYkJjGSJyh24mqoT0iEIgJrbjdBMhb9C4mbfYVWXnEB%2FqegGwTAsHKJEaOHHwrB1yX%2FSzBP8z4Tu4sR96EecR%2F5hmLLvq2LI83ggnCdkt51crKJAt6deN9IQ7luRxLI1MNVasV6%2BqlG41JZ07ZzAf4luYd0qNmIXDqwy6F6naeo%2FEQZcS6sbbtu4yS%2FCCSQf02tOK3xmR9NGHh3PQTcN4052VZtyePG%2Bw8ztMtg6yaOVbRCdF5CtGY5CSmAWqFmtTSklOnyDWlAxfNZSVNnARelFpxV5EucIUuKNZUYSUqKzaCN%2FiyfJ46QbHX4C8r6QtjsGAAA%3D">CounterMutex.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzW7UMBB%2BlVFOG1HcFhCHiCK27QIrtVB1K%2BAQCXmTycaq145sZ7fVaiVuXDnw8ybwPn0SxnbS3XLlgEqUKNF4PN98M%2F4mq6RIsmR3F26%2BfbnXd648ie8%2FYXh%2BMT46GcHow%2FD07GSUgasRCl0ilMIWrbVYglDByo0ThcS49V8T%2BGv%2BuRLzRhsHx8I23BW1N1WtKkBqXr7jssVBCtxek%2BXhcxgrByt48gjWwU8oLqGQ3Fo41FcZvKCNNRaXVK0JqpJPJcIqV0DXght6KBwcwF6uwn6q4HsunIVKmw5jqc0laAUcplKHQK42yEvWZVW0xqByfWJ9ShFDooNSKw%2FR05ngnDe1NjgI4BnspRvfqb4iV8p80BkvuL3sg%2FmLHFifNF9SqttV2bh5TGbFjKrRm9fxFVb8RsqV2B62sywSs8Sw0Vp29KK3QdcatUHdlOnm66d7fUcSPz7D8ej0Lbwenr8ZTSYZKO2gIUGBroK28IrPG4kMxmRS8hpMq%2BytFkMQAD7VC5KhKqExQrm4btC20jE4qrmaIVCnKoNIETrVYimcNuw%2FKeatal%2FqlmTmhFbeGOoxyBM%2F0SbO15U7yPPBMXfIlF6mOXklqXf1x99rDY2ls31mdIHWjlWlWbP1zQsnFtitanNEaG4DEyCEmnmILlYKjiRkd8CrsEFDfTMYID2g047mRS%2BlpXC1F9wro9tmoKvMS5lZlFVKM2bmrdS9qAw%2FID76Xu4x9qzPe0uowZvxsowK%2FnNMrO%2BI0o8i287jIOqjx5yi2Aknwq%2BC34ODzr6%2BI1NaCgLtyzGUMrIHmovC1ljueJ%2FMlycwT7vah3%2FOL7gw1xnY0Kae0UPYjyEYDMMB3p4RGzEIpdB0agiEvRj8AvVuZvi8T4D6sKxFUYOwUOsludDHtJ1BLUq0QRponSVVJDvJgn7pT9ljtp%2BsfwMYXxQt4AcAAA%3D%3D">TaskSemaphore.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91VzW7TQBB%2BlZFPsQjbFBAHiyJFaYBILVRNhDhYQlt7nKzizFq764QoitQbVw78vAm8T5%2BE2fWGVogbB1QsS4lmZ%2Bab%2BWa%2B9S4pkiw5OoKbL5%2Fu9ZuTb%2BLrdxheziajszGM3w3PL87GGbgFQqFLhFLZorUWS1AUrNI4VdTYhf7rBv66%2F5yqlgqotSzfyrrFXgrSbtny8DlMyMEOnjyCvffjdqetbZBKG3hw0i5BUgmVQbSgnDcblKWIOYvWGCT357Q5AT9yI5W7C57TAevm8%2FW9frsmvn2E0%2FH5G3g1vHw9nk4zIO2g4RUCXQUW8YNcNTUKmLCJ6i2Yluyv7QtJmKYrvcbAdWMUue7coG1rJ2C0kDRH5j8MgjPEPcVSOW3Ef0JmTmrVaObthW6plE5p8sbARy9PvIanzvMqHeR571Q6FKQ3ac5eSepda3Sw0WaJxsIJXBhdoLUTqrRo7vyXhVNrjKfajBjN3cIECEVzDxFzpUEIts%2FTQ2jQ8NwMBkgP6LSTNcN1i75RbjFj75dGt01PV5nXgrBYVykLbe6tPL1OGpU28N7PciDEs0PdUTb%2BCd5ClqVPyNEdwm%2Ba23f%2B8WctDdh2xeUMbjG6uLUP8GhdEbvg9%2BAk2mO8Qdca8kdBpgdShnXdcQCVImUXWPa9T%2BZJCv2ncQLhrv0BM7PNwIZhHQ8GMVSRdXx3eFnEZgXMFrjlTOHOASN5qQ1vtqSoiqtaF0uG0mHdeYhzI1ecWHE9sRLL65%2F0kzV%2FrZ6Kx%2BI42f8ETATCc7sGAAA%3D">TaskAwait.swift</a>, <a href="https://swiftfiddle.com/?c=H4sIAAAAAAAAE91X224bNxD9lYFQoLuAspFRoEUEK6gaqagBO00toyhgGQG1O9ISXpFbkqtLDQN962sfkvRPmv%2FJl3RI7k0XG037lMh6sMm5npk5Q9914k6%2Fw5e5VAZGXOfMxOlUlAeTrYhTJQX%2FjRkuRX3%2BvSxEUh5NxdOnMMKMz1Axg9kWCo0aGGhcsjyVCoHZPzMZ38JcKjApnSjD4wy%2F1BDLZc4U11JEztIwy4DFMWoNXIOuA8CkC7PCOO3GckqmhQS5FlwsnphUIUvIpDCKxYYMzrlgGcQZI3OTSusStSxUjH34tiDzGN9iQreU0SxDuJsKoE%2Bu%2BIrSgQwNLOwvgxqe2lCwYllBZk7CXZ0VU0DwsD5cT4yiyG5I%2B%2FrGYmXF5uQVWJ6Tx%2BA1lDa8YFi5tx%2FrNlozboKwOUxwjgru%2FKXmC8ovCOG%2BJUCOo9K6s10q3%2B%2B414LlOpVkGp48b8L8394VmkIJF0Tt1nluV%2BKiMLhpqvAY9NYQgec0TqswnwfXN%2BHHoulwWXOTnttGvCMv0mBsMBlZF1w0kj6G1u0xOMvc%2Fguy%2B5F80WtZui8n6sPbPz%2Fpr0%2Fi3d8wvLw6e3E%2BhvEvw4tX5%2BO%2Bm%2BBYJggJ13GhNQ0fF21W%2BEzyLws5TBINheC%2FFui7U8NcyaVlqbhQCoWBtVS3qHQXLH3puoM0rFNOY0HQbJ0pRoynDSeGXCtuqK26wATxnaUwTWLMwEyalMz40dJwi7kBXKHaet%2BWEm2T0gmfb6sR1AE3lryJz3UfziiiAZz0Xvd6vXqC7CzqfQIlsQNSrdjCKizbc15NcVvQi1a8%2BlOBFGGDyytUtC%2BWO8E1v1No1DcJbnZm17p1mdrY3OgFTqg1tQdpPDTeO%2BHvCzViVJjxBlXMNZYF9GWjShBXlrU9rF3UWOBzn0nE9UWRGZ5nGMh5H549%2B2aHwjwxISGUcItBcJhKwz4EZEGVPB20MXvE1m62%2F9rOPgfaAuAmd9zp%2BsMEQS%2BKTlvKEQUd%2BOJEXHAThkd67Gc%2FKoMj5Wpi22u1WuehXKr9cgxCr1xmOziS7SFaH6diodjzFlqtCq2HdFqujstzYYJp57vdyadFzLigGjBquek0aA%2FODhtF086epauUXl4lqSR%2BORpcUNduu%2FTYohrRXVJkVD6g5xxpSXtHUtTv3DBBkDub9Sp78%2Fsn%2FfVJ%2FPUHjMYXP8IPw8uX48mk76Cgp6sBOXfbCzdsSZMbwRkdCXoHq0Loets5IwBsJlfoWNuh7e%2BpajT2EbxImVggtRFtCLQv6XIvInWDVNFnAqb9qVrNPhAmxoJIu4u6dGTflUKuwylJdRzN7q%2BqsOqqd%2B%2FhSm37ENsOf2yhnfT8LnOV8Ryc0zMU6cquy7Iy7mlKg7MomErKnen%2FEemCllSHZigenAcqUafbWdF%2FVF9HX0Unnft%2FADmMjadfDQAA">main.swift</a></li><li><a href="https://plantuml.com/timing-diagram">PlantUML: timing diagram syntax</a></li><li>Diagram sources: <a href="https://www.plantuml.com/plantuml/uml/ZLRRajf647tNLtH8gd8f5yibm5u8WGKHgipQBZjRUTmQf0OcEvgXPaR6nENtFESJyoNf6Ga1Gcoy3rkYkyyvCtsJXiOoRTD41D_3RoXHCuinBBLAO9skL7t74W5Cnc3N21J98u7mKKLiaGgcTtUWKmacqdnZpPL66QD-YZbRQPOyCMFGcdhofwa7ttotMC4lKFjswlzgPB3uoNfJgz5gjswSAKcTkhDrMzrnpzi4b-XDazva7BQTIM9gDHDFIow4TuNXj3NjETU6IHGbeJLVhP-uVFRcyKrhr0aBSq4nlNSa_X0OypGf0DUZJhFHE78S8E7qElHKGcsB-5QdsmxlzzRZ8xQdaymSFHVHlN5x51xC1-vEE9rwxcYJ5j6DHZVitkoj1-vxugRCc6SkDunI3miMFQ-qIcKyLa9feEmVUMDSibJOgP8sTxjQ70LORWLUTWjSKQNlone-z-TXIbDJv26kc6SHbuL6MgjjxlAzKVPTXcgCB9ChWIVwPP8YgapKDtOdS11Odd2vccGT3Py3W3bTuOGDe0p-4lIl2Znb4jvfhZItE-3o8sh3bRo5VkGGjqVjDdZmZ_qhxnbGcGJR6Jzv6erATOIWjZIZrQLymnAah70cglqV-5y8pSwHqwnPhBPqFrWoOQWm4QF3De4Pw7LXmp-XC46aPCGDGgs_6EpFl6_XWNlOdxT_jHZK7FPr9MO_XOCPFPnXPfMOYxafS0yNpkVdSJ1NssC4_E3JzwD7pYkH-RGDnkyUpxJ6mR0Hl0Pke3P34SDY1oHGWsBGWvbtZen0t93zU4y53zxtHbag9ejtPVVSk-UKJtFCECxD9pB3PgxamdybJx7ASfhtkS8PJJbysCgP_c3S6bXI2sTQXv3itEzJAQbHo7Eq1NFQh3Gbrx2R8oTAOlLb3vp_SzthKjPT1rNS-b6wTiIuh3OhgHrmcTmPtR2Pr_dpciSnoYyvHTLLnYTnmsPUciBoSF9hVl8hMt-mKDOgjmoNbfR9MthTlT2Dhs19Snd39bif7CrXbLIE60o-OjKSOYf6fqwdUbbYwxhd5gxXtx__WHQzaxgGIZBTVOLqn5A3XX1xxC-Wbcxf9Kxt9tXqHFJfWI2LfSt91BsUQDDvWLVE20aLWWQPvZasG2tCttw019b9DIOewHF44_s-HdXnWG6zK6WdgctLphrxgIWvQhjMhhuwwxHwGCNDIXmCwP_xoFeF">inversion</a>, <a href="https://www.plantuml.com/plantuml/uml/XLPVazes47_tfzZIpZHfCnoO0BaBfN1WoamWpJIzwUEDi0LMaIL6akFGJDxxt8_OJzALx3F6-2WFOFQt-zlL_fCdsX1bqeHxtyClL51538rWgsG2SRgJxID9E10HWOafe2OBEOLFCYIRb1DrV0ig5Q13nGv6toWg8geU8qPsYYIFH6jgT3lvKxUzRxxRxE0dQ7sxS9yM2WpzR9p8x_Wz_zQAajHwjxA1FvWDdOmpGPreFfpFWfuL2PeQHVZZbd7ke21O-8kXXGv4K5vp5BDT_CZ4tebdj_wq7vJYac9nRqbS43HYQL8Ql9dskvrE1JYP18itWQFYCYlr_VwW5zm_IQiXzXRpN1pkI-tXh3SDJk8JTpzOB1ntU4XBxKvd40nkdwGdxdlanipeFHC7Wgc73GdtEoLJ4Sqabmem-nKqebkIShEGmXImhKL5mJ33wVCmfpkiz7tTXylzfPfKs1I5YYtcXSRpZgPAoQo0N6_KiUTD5GqD4JjEp_pNIKgjEj58coEdOy-mX8dTFEze-E81hF08Psm0TUEltkYcjCTCmWV5f6Bc24p451-82EcT6ocPuSp13kS4avvGC1AsJ30TDvVhFK6TgMA4D-CVsLyKklqAg6CIoGpF05l2DIO_91XG5uY6uG0Ex3FbsWkb29ccq1fjngFGdkIkRDEnVHZTEEbuTBCPjwpjkqQRfqaRB_7XmcRPQ7CQj_7QFLxOhP-9pytSU2MpgWMyS2bzwInNZPR5H8rd7nukVCsyISTx1qn3Qqbv19iZe8CMbCFiBHqurPpI0yghkyXRE-ozDDXO93hMuPM3LvXFNMMS5U8pDvDkuScg_un8kQuAcjyA3nSqTVM9Np3zGHYssHRRDFTrKbcVCLRst9ElL0ZRGZ_2Hafj6eDl0YUlQxcqVT5mbWTXcun6hq38akKiTSjg76SCUG0Nn9D1xlfBpAA8Ygy5mrmAsbor4tVr_3bxtfWrQDBj5APDfBCpvvDkKSvIiZxxjphxbwz5J8GnqYx9hS4bypjk2st7NqZ3f20SCgdsa34Jmw5nlroPb6B9K0ss9V3wneiT6JMkG-G6BV54wXLwjLV_rUa6G_P8OtUPhQ6T8MjjVw_vLvHJeft_zlyuo6pRti5h-FVlVy372y-7LDYmNp2X3VOio2qCNhOnsX_WmI54LTBazggpiErb8C7ou4h0pH1fm65Wltw418D95Ksem1SMHsJJVNKL0bu_k5rbbXzUKIrJ5HOR_IrSMJQ5LHPBMtMLzrtRmvBdXVSc-6LVoVu3">inheritance</a>, <a href="https://www.plantuml.com/plantuml/uml/fLLHRzis47xNhxXb0zO2Y-FOYDEadbV7bjA7k2YM5djOXe2cpX9dYXH8geetxB_lIDcox2HxcHy4-hlZTyVlxiWFrZ7Zga96Fy8jAZJCOGeheml8gqptDgoGm5GABaSWJy4bmZVDsRAIp6pUWwaKM6v4wUoPGPMYUKm5ommh7fcrw6ol-DFsekz-M6RmCvnyduJV2G4Edro01lt1S73beQBoqJqs6encbm6JGc60vfVpMJpqaCBA6IOVLqBAO8hZP91SUbF95CgZGBd8yaUXrW6UNGsc5t4BjnJ9ZIS9IM0gggBTy6vwSTxlTmpxBN7oBWvKKjUj_-1YD8nlTcWtnM4oRs2-RhqlPyDfl8Vtt1TnaWHkNbQjTxy_YaTNEtJFVKFSf8nT2rKoaXwMZAypeokLphJK1aZzZZN55QkaIxHoMxElHSV12IVnTRF4Z2fzSnmZQF_SJHjgYgsBB-OpZzS3JOtHzTOKUkFOzlfMWzmnbKayY7zCqdeT4usjsqYSH4uKGcNpfgFXxmZWZevmm0PmlFcVQ7pMxYSbuOk676KPXaZND6K_XQNTM8SqQCo2qx1MkeOwro0S2FjokJwn0kdaWicNxVVYBuJpKSTeSvRgciu0AoOjldJsNviQ6ieBpWUHn9Np-HYQ3mUfy7v2gwZrXvEvi2LpFB_7WfMvDdW2T8Rxso1Gns-yd8ov5-Qw7SB9HrgCpm8w6Pyj9m-gPiBPXk4ZxCVoaEepcaAu1rKfzeq9oPPo6nGEheF3JR-HchMV4ixeOqMcc7ppzfS7zONKvwINOTnv_QYc5fHkYjFmtZqZfknEJoSKyHfyoc_UUWnwlObtlcwt0pNvcdgWayU26kK9j88vCrIB463nlzLQlAvMXsfttKpkQ7549LmEB3IUwXnzyHNsjz5_yDPRslgGDTSojQ6_dwKWEoaqeUwWlIOfqg9Hc18WYIavdxA7lpQmLpcasRXwvGEMOkbV7iKtiDBcGPL6Q2FS1eJAaHPCSQI2K7-U_fwBb3p_e9bGdl8sQkuWM6hdT474Kx2xhgOMgPIpK8RUi-z9go9KSjSnzAzY4l29oyhIZ8INCcHeSr7sYCqtcYsHYvNWz4xcc5RI3sEffQ1qcyojRmqlc2XAYGKgnzoEpSEbP8uELlGYScxoZJxGnp_R_m80">owner dependency</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47647c72fe8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Rebuilding Loading, Success, and Error UI in Every iOS App]]></title>
            <link>https://medium.com/@mykola.dementiev/stop-rebuilding-loading-success-and-error-ui-in-every-ios-app-1ede922039b9?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ede922039b9</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[retry]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[loading-screen]]></category>
            <category><![CDATA[uiwindow]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 16:29:54 GMT</pubDate>
            <atom:updated>2026-11-07T09:11:21.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zFbr8_qinUhyon4gxI9oQ.jpeg" /></figure><h3>Configurable defaults, replaceable state views, and a shared presentation layer for SwiftUI and UIKit.</h3><p>Add a spinner to a Save button, and the loading UI looks nearly finished. Then the operation needs a success message, an error with Retry, a way to close the result, and rules for what the user can tap while it is running.</p><p>A sign-in request and a document save do different work, but their feedback often follows the same sequence: loading, then a result, then dismissal or another attempt. Rebuilding that presentation in each feature spreads its behavior across the app. Reusing a fixed set of views becomes awkward when the next design needs a different indicator or error layout.</p><p>I wanted a common way to show those states, with defaults I could use immediately and state views I could replace individually. The feature should supply its result and decide what Retry does. The presentation should handle showing the chosen view, dismissing it, and controlling interaction with the content beneath it.</p><p>That is the scope of the HUD in this article: temporary loading and result views over the current app content. I will use a save operation to show the separation, then explain the implementation choices, including why I put the HUD in its own window.</p><h3>Separate the operation, its state, and the views that display it</h3><p>There are two kinds of reuse here. The behavior should stay consistent when several features use the same feedback flow. The appearance should remain replaceable when those features, or another app, need a different design.</p><p>I split the responsibilities at the points where they change for different reasons:</p><p><strong>Application</strong><br><strong>Responsibility:</strong> Runs the work, handles cancellation and late results, and decides what Retry does</p><p><strong>Presentation manager</strong><br><strong>Responsibility:</strong> Holds the current UI state and applies result-dismissal rules</p><p><strong>View provider</strong><br><strong>Responsibility:</strong> Supplies the loading, success and error content</p><p><strong>Presenter</strong><br><strong>Responsibility:</strong> Attaches the HUD and handles its display and input</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHFZYmcWR-xjwRWPfxAOXg.png" /></figure><p><em>These are presentation responsibilities. The application’s operation runs outside this layer.</em></p><p>The manager can use the same success state whether its content is a checkmark and text or a view from the app’s design system. The presenter can keep its attachment while that content changes. Neither needs to know whether the result came from saving a file or signing in.</p><p>This also gives customization a practical order. Start with the default views. Change their settings for small design differences. Replace one state’s content when the layout needs more freedom, keeping the other defaults. Replacing an error view should not require another implementation of presentation and dismissal.</p><p>The app decides when work starts, supplies its result, and chooses what happens on Retry. The manager applies the result-dismissal policy. A presentation manager is not an operation queue or a task executor. In this design, one manager holds one current state; several simultaneous tasks need the app to decide which one that state represents.</p><p>The scope matters too. A modal HUD suits an operation that must keep the user in the current flow. If the rest of the screen should remain usable, an inline progress indicator is a different and often sufficient choice.</p><h3>How I packaged this in DMUnLoader</h3><p><a href="https://github.com/nikolay-dementiev/DMUnLoader">DMUnLoader</a> is the implementation I built around those responsibilities: a manager, a view provider and a scene-bound presenter. Its separate window handles placement and input; I will return to that mechanism after the state and customization examples. It supplies loading, success and error UI for SwiftUI and UIKit. The examples below use <strong>DMUnLoader 1.1.0</strong>, with <strong>iOS 17+ and Swift 6.2+</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WjdwGxPCvJHwxcck.jpg" /></figure><p>The loading manager exposes four operations:</p><p><strong>showLoading(provider:)</strong><br><strong>What the default UI shows:</strong> A loading view until the app changes state</p><p><strong>showSuccess(_:provider:)</strong><br><strong>What the default UI shows:</strong> A success view with the supplied result</p><p><strong>showFailure(_:provider:onRetry:)</strong><br><strong>What the default UI shows:</strong> An error view with Close and, when provided, Retry</p><p><strong>hide()</strong><br><strong>What the default UI shows:</strong> No HUD</p><p>One manager holds one state at a time. The supplied success value conforms to DMLoadableTypeSuccess; String already does. The default success view uses that value’s description. The default error view uses the error’s localizedDescription along with the title and controls from its settings.</p><p>These calls present HUD content rather than navigate to another screen. While a state is shown, the HUD takes touches over the app content beneath its window in the same scene. Success and failure retain that modal behavior until dismissed. Placement relative to other windows depends on the configured window level.</p><h3>Connect it once at the scene root</h3><p>Add https://github.com/nikolay-dementiev/DMUnLoader in Xcode’s package dependencies and select 1.1.0 or a compatible release. This example connects a manager and provider at the scene root. The Save action owns the work and explicitly updates the HUD:</p><pre>import DMUnLoader<br>import SwiftUI<br>import UIKit<br> <br>@main<br>struct LoadingDemoApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            DemoSceneRoot()<br>        }<br>    }<br>}<br> <br>@MainActor<br>struct DemoSceneRoot: View {<br>    @StateObject private var manager = DMLoadingManagerMain(<br>        state: .none,<br>        settings: DMLoadingManagerDefaultSettings(<br>            hudWindowLevel: .normal + 1,<br>            backdrop: .dim()<br>        )<br>    )<br>    private let provider = DefaultDMLoadingViewProvider()<br> <br>    var body: some View {<br>        DMRootLoadingView(manager: manager) { manager in<br>            Button(&quot;Save&quot;) {<br>                saveChanges(using: manager, provider: provider)<br>            }<br>        }<br>    }<br>}<br> <br>@MainActor<br>private func saveChanges&lt;<br>    Manager: DMLoadingManager,<br>    Provider: DMLoadingViewProvider<br>&gt;(<br>    using manager: Manager,<br>    provider: Provider<br>) {<br>    manager.showLoading(provider: provider)<br>    Task {<br>        do {<br>            // Replace this delay with the operation you own.<br>            try await Task.sleep(for: .seconds(1))<br>            manager.showSuccess(&quot;Saved&quot;, provider: provider)<br>        } catch {<br>            let retry = DMButtonAction { [weak manager] in<br>                guard let manager else { return }<br>                saveChanges(using: manager, provider: provider)<br>            }<br>            manager.showFailure(error, provider: provider, onRetry: retry)<br>        }<br>    }<br>}</pre><p>By default, the manager hides success and error after two seconds or on a tap, including failures that offer Retry. I will change that policy below so the failure can remain available until the user chooses an action.</p><p>The explicit window level places this HUD above normal-level app windows in its scene. The <a href="https://dementievmykola.com/blog/dmunloader_loading_success_and_error_screens/#why-i-gave-the-hud-its-own-window">window section below</a> explains the choice and its limits. The library defaults to .normal, so leaving the setting out does not make that same ordering promise.</p><p>The delay normally succeeds; replace it with the save operation whose errors you want to display. Retry calls saveChanges again, and that function explicitly switches back to loading. Its action captures the manager weakly because the manager retains the failure state and its Retry action. The presentation API runs on the main actor; the app still decides how to cancel work or discard a late result.</p><p>DMRootLoadingView(manager:content:) needs no app delegate supplied by the SDK. Keeping its @StateObject inside the scene root gives each root its own manager, which matters when the app has several windows. An app-level shared manager would share its state too.</p><p>There are also delegate-based integrations for SwiftUI and UIKit. UIKit requires a scene manifest, a configuration using DMSceneDelegateTypeUIKit&lt;Helper&gt;, and a helper that creates the root controller and receives its loading manager. After that setup, the UIKit screen uses the same state calls and providers. It can call saveChanges(using:provider:) with the manager supplied to it; this part of the feedback flow does not depend on a SwiftUI view body. The DMRootLoadingView(content:) initializer without an injected manager creates a manager and requires the SDK’s app/scene-delegate bridge; the injected initializer above does not. The <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/1.1.0/README.md#usage">README for 1.1.0</a> has complete examples for both frameworks. Use one integration per scene rather than installing the injected and delegate paths together.</p><h3>Customize the defaults, or replace the state views</h3><p>I do not need to write three new views just to change one icon. DefaultDMLoadingViewProvider accepts separate settings for loading, success and error. Each settings type exposes the properties used by its corresponding view: text, colors, images and layout.</p><p>For example, this provider keeps all three standard screens and makes the success icon mint:</p><pre>import DMUnLoader<br>import SwiftUI<br> <br>@MainActor<br>func makeMintProvider() -&gt; DefaultDMLoadingViewProvider {<br>    DefaultDMLoadingViewProvider(<br>        successViewSettings: DMSuccessDefaultViewSettings(<br>            successImageProperties: SuccessImageProperties(<br>                foregroundColor: .mint<br>            )<br>        )<br>    )<br>}</pre><p>In the Save example, change the provider declaration to private let provider = makeMintProvider(). The state calls in saveChanges stay the same. The loading and error views keep their defaults because their settings were not replaced.</p><p><strong>DMProgressViewDefaultSettings</strong><br><strong>Examples of what they control:</strong> Loading text, indicator properties, container color and reference size</p><p><strong>DMSuccessDefaultViewSettings</strong><br><strong>Examples of what they control:</strong> Success image, text styling and spacing</p><p><strong>DMErrorDefaultViewSettings</strong><br><strong>Examples of what they control:</strong> Error title, image, buttons and layout</p><p>The success message still comes from the value passed to showSuccess. Changing SuccessTextProperties.text does not replace that payload’s description. For a different arrangement or a different indicator, a custom view is the next step.</p><h3>Replace one state view, or all three</h3><p>DMLoadingViewProvider has three view-producing requirements. Each has a default implementation, so replacing loading does not force me to write success and error as well.</p><p>To give Save its own loading content, this provider only implements one method:</p><pre>import DMUnLoader<br>import SwiftUI<br> <br>final class SavingViewProvider: DMLoadingViewProvider {<br>    @MainActor<br>    func getLoadingView() -&gt; some View {<br>        VStack(spacing: 12) {<br>            ProgressView()<br>            Text(&quot;Saving your changes&quot;)<br>        }<br>    }<br>}</pre><p>Set the root’s declaration to private let provider = SavingViewProvider(). Success and error now use the protocol’s default implementations. This is a replacement provider, so it also drops the mint setting from the previous example. The Save function and its Retry action do not need to change.</p><h3>Supply custom content for every state</h3><p>When the design calls for custom success and error layouts too, the provider can implement all three methods:</p><pre>import DMUnLoader<br>import SwiftUI<br> <br>final class BrandedScreens: DMLoadingViewProvider {<br>    @MainActor<br>    func getLoadingView() -&gt; some View {<br>        VStack(spacing: 12) {<br>            ProgressView()<br>            Text(&quot;Saving your changes&quot;)<br>        }<br> <br>    }<br> <br>    @MainActor<br>    func getSuccessView(object: any DMLoadableTypeSuccess) -&gt; some View {<br>        Label(object.description, systemImage: &quot;checkmark.seal.fill&quot;)<br>            .foregroundStyle(.green)<br> <br>    }<br> <br>    @MainActor<br>    func getErrorView(<br>        error: any Error,<br>        onRetry: (any DMAction)?,<br>        onClose: any DMAction<br>    ) -&gt; some View {<br>        VStack(alignment: .leading, spacing: 12) {<br>            Text(&quot;We could not save this change&quot;)<br>                .font(.headline)<br>            Text(error.localizedDescription)<br>            HStack {<br>                if let onRetry {<br>                    Button(&quot;Try again&quot;, action: onRetry.simpleAction)<br>                }<br>                Button(&quot;Close&quot;, action: onClose.simpleAction)<br>            }<br>        }<br> <br>    }<br>}</pre><p>To use it, change the root’s provider declaration to private let provider = BrandedScreens(). The calls to showLoading, showSuccess and showFailure stay the same.</p><p>The state content is now mine. I can use a design-system component, change its layout, or supply a different loading animation. The <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/DMLoadingViewProvider.swift">provider protocol</a> shows those defaults.</p><p>The SDK still wraps the provider’s content in its shared rounded HUD card, with its own padding and background. That is why these examples supply content without adding another outer card. The provider replaces a state’s content; backdrop and interaction policies are configured on the manager separately.</p><p>Provider methods build views and can be called more than once per state. Start work from the app’s actions, not inside getLoadingView(). A separate hosting controller also starts a separate SwiftUI environment tree: app-level environment objects do not automatically appear in custom HUD views. Supply the dependencies those views need yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FHrJYRT4w4TVPKE2.jpg" /></figure><p><em>The manager keeps the same states while the provider changes the content used to display each one.</em></p><h3>Decide how results leave the screen</h3><p>The default behavior is easy to overlook: success and failure hide after two seconds and on a tap. A failure with Retry has the same default. That can remove the retry opportunity before the user reaches it.</p><p>Here is a manager configuration that keeps retry failures until the user uses a button or the app changes state:</p><pre>import DMUnLoader<br>import UIKit<br> <br>@MainActor<br>func makePersistentFailureManager() -&gt; DMLoadingManagerMain {<br>    DMLoadingManagerMain(<br>        state: .none,<br>        settings: DMLoadingManagerDefaultSettings(<br>            hudDismissal: DMHUDDismissalRules(<br>                failureWithRetry: DMHUDDismissal(<br>                    autoHide: .never,<br>                    cardTapHides: false,<br>                    backdropTapHides: false<br>                )<br>            ),<br>            hudWindowLevel: .normal + 1,<br>            backdrop: .dim()<br>        )<br>    )<br>}</pre><p>In DemoSceneRoot, initialize the state object with @StateObject private var manager = makePersistentFailureManager() to apply this policy to the same Save flow.</p><p>Close still hides the failure. The Save example’s Retry action calls saveChanges again, which explicitly shows loading before restarting the operation.</p><p>The manager also rejects stale auto-hide callbacks, so a previous state’s timer cannot hide the next state. That protection concerns the timer, not the app’s work: an older request can still overwrite a newer result unless the host handles cancellation or checks operation identity. The <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Tests/DMUnLoaderTests/DMLoadingManagerAutoHideTests.swift">auto-hide tests</a> exercise the timer boundary.</p><h3>The actions and the backdrop are separate pieces</h3><p>DMUnLoader depends on two of my other libraries, each doing a smaller job:</p><ul><li><a href="https://github.com/nikolay-dementiev/DMAction">DMAction</a> supplies the callable actions behind Retry and Close. Its separate API also supports retry and fallback composition.</li><li><a href="https://github.com/nikolay-dementiev/DMVariableBlurView">DMVariableBlurView</a> provides the backdrop whose blur radius varies across the view. DMUnLoader uses it for the default variable-blur backdrop. The manager can instead choose .dim(), .material() or .clear.</li></ul><p>See their linked repositories for examples and details of action composition and variable blur.</p><p>The default variable blur uses a private system filter. Choosing another backdrop avoids constructing that effect, but does not remove the dependency’s private API references from the linked code. See DMVariableBlurView’s documentation when assessing that choice.</p><h3>Why I gave the HUD its own window</h3><p>The reusable state API still needs somewhere to present its views. I ran into a concrete problem with that part: the HUD was visible over an iOS app, but the tab bar at the bottom still accepted taps. The operation was supposed to keep the user in the current flow, yet switching tabs remained possible.</p><p>That made me check two things separately: where the HUD draws and where it receives input. A screenshot of full coverage does not establish both.</p><h3>A view can cover an area without owning its taps</h3><p>An <a href="https://developer.apple.com/documentation/swiftui/view/overlay%28alignment:content:%29">overlay</a> belongs to the view it modifies. In UIKit, the selected controller supplies tab content while <a href="https://developer.apple.com/documentation/uikit/uitabbarcontroller#The-views-of-a-tab-bar-controller">UITabBarController</a> supplies the tab bar; blocking the former does not automatically block the latter. For SwiftUI, check whether the HUD wraps TabView or sits inside one tab. Its private backing hierarchy is not a contract.</p><p>UIKit can draw a child outside its parent’s bounds without routing taps there: <a href="https://developer.apple.com/documentation/uikit/uiview/hittest%28_:with:%29">hit testing</a> does not enter a parent’s subtree for an outside point. Apple’s <a href="https://developer.apple.com/library/archive/qa/qa2013/qa1812.html">QA1812</a> describes this case. It is one possible explanation for visual coverage without input coverage, not a diagnosis of my original app without its hierarchy and a reproducer.</p><p><a href="https://developer.apple.com/documentation/swiftui/view/ignoressafearea%28_:edges:%29">ignoresSafeArea</a> changes layout, <a href="https://developer.apple.com/documentation/swiftui/view/zindex%28_:%29">zIndex</a> changes display order, and <a href="https://developer.apple.com/documentation/swiftui/view/disabled%28_:%29">disabled</a> affects interaction within its view hierarchy. <a href="https://developer.apple.com/documentation/swiftui/view/allowshittesting%28_:%29">allowsHitTesting(false)</a> removes a view from hit testing; it does not turn that view into an input shield. Each still depends on where the HUD is attached.</p><p>An overlay at the right common ancestor can work. If all I need is to block a tab container, moving the barrier around that container may be enough. I also wanted a presentation boundary that could cover app presentations beyond one feature’s view hierarchy.</p><h3>A scene window gives the HUD its own presentation boundary</h3><p>Federico Zanetello’s <a href="https://www.fivestars.blog/articles/swiftui-hud/">Custom HUDs in SwiftUI</a> separates HUD state from individual feature views. His follow-up, <a href="https://www.fivestars.blog/articles/swiftui-windows/">How to layer multiple windows in SwiftUI</a>, demonstrates a root HUD being obscured by a sheet and moves it into another window. Those 2021 articles inspired this part of my implementation.</p><p>The presenter adds a UIWindow to the existing <a href="https://developer.apple.com/documentation/uikit/uiwindowscene">UIWindowScene</a>. App content and HUD remain in the same scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbgcWW8HEiX2RrMUtNpZTA.png" /></figure><p>The presenter retains the window, gives it a UIHostingController, and makes the hosting view’s background clear. It shows the HUD with isHidden = false. Calling makeKeyAndVisible() would also request key-window status, a separate responsibility described in <a href="https://developer.apple.com/documentation/uikit/uiwindow/makekeyandvisible%28%29">Apple’s documentation</a>. Showing a loading layer does not require that request.</p><p>The window’s level is an explicit decision. For app windows at .normal, a HUD at .normal + 1 sits above them. Ordering between equal-level windows is not guaranteed. Neither setting means above every custom window, the keyboard or system UI. That limitation comes from <a href="https://developer.apple.com/documentation/uikit/uiwindow/windowlevel">windowLevel</a>, not from the appearance of the card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hoIx37crZ1cePPoq.jpg" /></figure><h3>The empty-looking area must block input too</h3><p>This HUD uses a modal input policy while a state is visible and passes touches through while idle. A reduced version of the SDK’s <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Helpers/DMPassThroughWindow.swift">window policy</a> connects that rule to presentation state:</p><pre>import UIKit<br> <br>@MainActor<br>final class ModalHUDWindow: UIWindow {<br>    var showsHUD = false<br> <br>    override func hitTest(_ point: CGPoint, with event: UIEvent?) -&gt; UIView? {<br>        guard showsHUD else { return nil }<br>        return super.hitTest(point, with: event)<br>    }<br>}</pre><p>Set the flag before showing the window, then keep it synchronized with the presentation state. Idle returns nil; a visible HUD uses ordinary UIKit hit testing.</p><p>The hosted root also needs a <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/DMLoadingView.swift">surface covering the window</a>, rather than only the centered card. Here is a reduced loading surface:</p><pre>import SwiftUI<br> <br>struct ModalLoadingSurface: View {<br>    var body: some View {<br>        ZStack {<br>            Color.clear<br>                .contentShape(Rectangle())<br>                .ignoresSafeArea()<br>                .onTapGesture { }<br> <br>            ProgressView(&quot;Loading...&quot;)<br>                .padding(24)<br>                .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))<br>        }<br>        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>    }<br>}</pre><p>The backdrop gesture consumes taps during loading. Results can connect it to dismissal instead. These reduced examples still need scene attachment, a hosting controller, retained ownership, and state wiring.</p><p>A clear backdrop can still block input. The state-controlled window and full-area hosted surface work together to enforce the modal policy.</p><h3>Keep scene ownership and accessibility in the same implementation</h3><p>The <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Adapters/OverlayWindowPresenter.swift">window presenter</a> binds the window to the scene that actually hosts the requesting root. The injected integration discovers it through <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Adapters/SceneHUDAnchor.swift">SceneHUDAnchor</a>, rather than taking the first connected scene. Use one integration per scene; installing two can create two HUD windows.</p><p>hide() changes the manager to .none. The empty window can remain attached and pass touches through. Removing an injected root, clearing the scene delegate’s manager reference, or disconnecting the scene performs structural cleanup. Replacing a manager reuses the presenter’s window and hosting controller. Those are ownership rules as well as display rules.</p><p>Touch blocking also needs an accessibility counterpart. The <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Adapters/AccessibilityAdapters.swift">accessibility adapter</a> hides other non-HUD windows already attached to the scene at the HUD’s level or below from assistive technology and later restores their original state. Higher windows and windows added after the initial snapshot are outside that scope. Announcements, focus restoration, the escape gesture and reduced-effects handling are separate parts of the implementation.</p><p>The <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/README.md#known-issues">README’s known issues</a> still matter when choosing the content: white content on the translucent default gray card can fall below 4.5:1 contrast, depending on the backdrop, and default loading text can clip at large accessibility sizes. Custom content needs its own contrast, text-size and VoiceOver checks. The 1.1.0 string catalog contains English defaults; the app supplies other text through settings.</p><h3>Other approaches split the same responsibilities differently</h3><p>For a small indicator tied to one screen, I would first consider a local view overlay. For freely designed messages with a queue, a message presenter has a different scope. Here the requirement is one modal loading/result state per scene, with state content that can be replaced. These choices determine which APIs are worth comparing. The following is a source-level comparison, not a performance benchmark or a ranking:</p><p><strong>A SwiftUI view overlay</strong><br><strong>State and presentation API:</strong> State and attachment chosen by the host view hierarchy<br><strong>How the UI is customized:</strong> Arbitrary SwiftUI content; the host defines input and dismissal rules</p><p><strong>DMUnLoader 1.1.0</strong><br><strong>State and presentation API:</strong> One manager with loading, success and failure; scene-bound window; SwiftUI and UIKit integrations<br><strong>How the UI is customized:</strong> Settings for each default state; replace any or all three state views through a provider</p><p><strong>AlertToast</strong><br><strong>State and presentation API:</strong> SwiftUI .toast binding with loading, success (.complete), error and other built-in types; view overlay<br><strong>How the UI is customized:</strong> Built-in styling and presentation settings; its content closure returns AlertToast</p><p><strong>ProgressHUD 15.0.3</strong><br><strong>State and presentation API:</strong> SwiftUI modifier and shared presentation/dismissal API with progress, results and other built-in types; view overlay<br><strong>How the UI is customized:</strong> Built-in animation, icon, color and font configuration</p><p><strong>SwiftMessages 10.0.2</strong><br><strong>State and presentation API:</strong> Message presentation in a view, controller or configured window scene; UIKit and SwiftUI support<br><strong>How the UI is customized:</strong> Custom UIView or SwiftUI hosting content, plus presentation and dismissal configuration</p><p>The relevant sources are <a href="https://github.com/elai950/AlertToast/blob/76a1c1793cd3443001c20c6033beb84453b25d9f/Sources/AlertToast/AlertToast.swift">AlertToast’s modifier</a>, <a href="https://github.com/relatedcode/ProgressHUD/blob/25471d6e1747f442e24bf0f4ace725a79648b418/SwiftUI/Sources/ProgressHUD.swift">ProgressHUD’s SwiftUI implementation</a> and <a href="https://github.com/relatedcode/ProgressHUD/blob/25471d6e1747f442e24bf0f4ace725a79648b418/SwiftUI/Sources/ProgressHUD%2BPublic.swift">public API</a> and <a href="https://github.com/SwiftKickMobile/SwiftMessages/blob/c0ff6c65bfc00e6a707957cb7069988c5cde2a30/README.md">SwiftMessages</a>. The comparison uses ProgressHUD 15.0.3, SwiftMessages 10.0.2, and AlertToast at commit 76a1c17. ProgressHUD’s UIKit 14.x line is a different implementation from its SwiftUI 15.x line.</p><p>SwiftMessages also supports an explicit <a href="https://github.com/SwiftKickMobile/SwiftMessages/blob/c0ff6c65bfc00e6a707957cb7069988c5cde2a30/SwiftMessages/SwiftMessages.swift">.windowScene(scene, windowLevel:) context</a>, so using another window is not exclusive to DMUnLoader. Its scope includes message queues and several presentation contexts. DMUnLoader’s API centers on one loading/result state, its three replaceable views, and the host’s Retry action. If that matches the app’s workflow, those are the boundaries to compare.</p><h3>Check the whole loading-to-result flow</h3><p>The repository has <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Examples/DMUnLoaderExample/AppTests/HUDWindowTests.swift">hosted window tests</a> and <a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Examples/DMUnLoaderExample/UITests/HUDControlsUITests.swift">interaction tests</a> covering window ownership, modal versus idle input, clear backdrops and a later normal-level app window. Those examples do not contain a tab-bar or sheet reproducer; those presentations need checks in the host app. The <a href="https://github.com/nikolay-dementiev/DMUnLoader/tree/1.1.0/Examples/DMUnLoaderExample">example project</a> provides a starting point for the integration.</p><p>For a host app, I would check the feedback flow with both the default provider and any replacement state views. Confirm the result text and layout, exercise Retry and Close, and verify the selected auto-hide and tap-dismissal behavior. A design change should not silently change those rules.</p><p>The presentation needs a separate interaction check. For an app with tabs:</p><ol><li>In the idle state, switch tabs and activate an underlying control.</li><li>Show loading, tap those same areas, and verify selection and actions stay unchanged.</li><li>Repeat with a sheet and a full-screen presentation already visible, using the app’s intended window levels.</li><li>Move to success and error. Verify Close, Retry and the selected dismissal policy without also triggering a control underneath.</li><li>Hide the HUD and verify interaction returns. Check the same sequence with VoiceOver and with independent scenes.</li></ol><h3>Conclusion</h3><p>The part worth reusing is the path from starting an operation to showing its result and letting the user continue. Each feature still owns its work, but it should not need another implementation of loading, result presentation and dismissal every time its design changes.</p><p>That is the separation I built into DMUnLoader. A first integration can use the default views; a new design can change their settings or replace individual state content inside the shared HUD card. The app still reports loading, success or failure through the same manager API. SwiftUI and UIKit use that same model, while the scene-bound window gives the presenter a place to handle display and input independently of an individual screen’s layout.</p><p>For me, the useful test of this design is a later change: can I replace the loading indicator or error layout without rewriting the Save operation or building another presenter? That is what makes the presentation reusable across features and apps, while leaving each app in control of its work and appearance.</p><h3>Additional Resources</h3><h3>Libraries and examples</h3><ul><li><a href="https://github.com/nikolay-dementiev/DMUnLoader">DMUnLoader repository</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/1.1.0/README.md#usage">DMUnLoader 1.1.0 usage guide</a></li><li><a href="https://github.com/nikolay-dementiev/DMAction">DMAction</a></li><li><a href="https://github.com/nikolay-dementiev/DMVariableBlurView">DMVariableBlurView</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/tree/1.1.0/Examples/DMUnLoaderExample">DMUnLoader example project</a></li></ul><h3>Implementation and tests</h3><ul><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/DMLoadingViewProvider.swift">DMLoadingViewProvider protocol</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Tests/DMUnLoaderTests/DMLoadingManagerAutoHideTests.swift">Auto-hide tests</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Helpers/DMPassThroughWindow.swift">DMPassThroughWindow input policy</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/DMLoadingView.swift">DMLoadingView presentation surface</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Adapters/OverlayWindowPresenter.swift">OverlayWindowPresenter</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Adapters/SceneHUDAnchor.swift">SceneHUDAnchor</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Sources/DMUnLoader/Adapters/AccessibilityAdapters.swift">Accessibility adapters</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/README.md#known-issues">DMUnLoader known issues</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Examples/DMUnLoaderExample/AppTests/HUDWindowTests.swift">HUDWindowTests</a></li><li><a href="https://github.com/nikolay-dementiev/DMUnLoader/blob/7b797cf73d94726568490906ef00b44a6a25c7e5/Examples/DMUnLoaderExample/UITests/HUDControlsUITests.swift">HUDControlsUITests</a></li></ul><h3>Apple documentation</h3><ul><li><a href="https://developer.apple.com/documentation/swiftui/view/overlay%28alignment:content:%29">SwiftUI overlay(alignment:content:)</a></li><li><a href="https://developer.apple.com/documentation/uikit/uitabbarcontroller#The-views-of-a-tab-bar-controller">UITabBarController view hierarchy</a></li><li><a href="https://developer.apple.com/documentation/uikit/uiview/hittest%28_:with:%29">UIView.hitTest(_:with:)</a></li><li><a href="https://developer.apple.com/library/archive/qa/qa2013/qa1812.html">QA1812: delivering touch events outside a parent view</a></li><li><a href="https://developer.apple.com/documentation/swiftui/view/ignoressafearea%28_:edges:%29">SwiftUI ignoresSafeArea</a></li><li><a href="https://developer.apple.com/documentation/swiftui/view/zindex%28_:%29">SwiftUI zIndex</a></li><li><a href="https://developer.apple.com/documentation/swiftui/view/disabled%28_:%29">SwiftUI disabled</a></li><li><a href="https://developer.apple.com/documentation/swiftui/view/allowshittesting%28_:%29">SwiftUI allowsHitTesting</a></li><li><a href="https://developer.apple.com/documentation/uikit/uiwindowscene">UIWindowScene</a></li><li><a href="https://developer.apple.com/documentation/uikit/uiwindow/makekeyandvisible%28%29">UIWindow.makeKeyAndVisible()</a></li><li><a href="https://developer.apple.com/documentation/uikit/uiwindow/windowlevel">UIWindow.windowLevel</a></li></ul><h3>Articles and alternative libraries</h3><ul><li><a href="https://www.fivestars.blog/articles/swiftui-hud/">Federico Zanetello: Custom HUDs in SwiftUI</a></li><li><a href="https://www.fivestars.blog/articles/swiftui-windows/">Federico Zanetello: How to layer multiple windows in SwiftUI</a></li><li><a href="https://github.com/elai950/AlertToast/blob/76a1c1793cd3443001c20c6033beb84453b25d9f/Sources/AlertToast/AlertToast.swift">AlertToast modifier implementation</a></li><li><a href="https://github.com/relatedcode/ProgressHUD/blob/25471d6e1747f442e24bf0f4ace725a79648b418/SwiftUI/Sources/ProgressHUD.swift">ProgressHUD SwiftUI implementation</a></li><li><a href="https://github.com/relatedcode/ProgressHUD/blob/25471d6e1747f442e24bf0f4ace725a79648b418/SwiftUI/Sources/ProgressHUD%2BPublic.swift">ProgressHUD public API</a></li><li><a href="https://github.com/SwiftKickMobile/SwiftMessages/blob/c0ff6c65bfc00e6a707957cb7069988c5cde2a30/README.md">SwiftMessages README</a></li><li><a href="https://github.com/SwiftKickMobile/SwiftMessages/blob/c0ff6c65bfc00e6a707957cb7069988c5cde2a30/SwiftMessages/SwiftMessages.swift">SwiftMessages window-scene context</a></li></ul><p><em>Originally published on November 6, 2026 at </em><a href="https://dementievmykola.com/blog/dmunloader_loading_success_and_error_screens/"><em>dementievmykola.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ede922039b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static vs Dynamic Framework Dispatching (Part 3 of 3): Debug, Release, @rpath, and the debug dylib]]></title>
            <link>https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-3-of-3-debug-release-rpath-and-the-debug-dylib-0f3d29ab495d?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3d29ab495d</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 19:27:44 GMT</pubDate>
            <atom:updated>2026-10-26T11:12:30.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Real-world edge cases in static and dynamic linking, part 3 of 3" src="https://cdn-images-1.medium.com/max/1024/1*EhLRYX4rC9UBrsssAWbjOQ.jpeg" /></figure><p>This is Part 3 of a three-part series:</p><ul><li><a href="https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-1-of-3-dispatching-under-the-hood-01a4f5996342">Part 1: Dispatching under the hood</a></li><li>Part 2: <a href="https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-2-of-3-spm-vs-xcode-frameworks-94b3fbded041">Hands-on experiments with SPM and Xcode frameworks</a> (3 October 2026)</li><li><strong>Part 3: Debug, Release, @rpath, and the debug dylib</strong></li></ul><p>The app builds. I press Run in Xcode, and it works. Then I launch it without Xcode and get:</p><pre>Library not loaded: @rpath/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic</pre><p>That was the symptom that sent me back to the binary. The app linked against the framework, so why couldn’t the loader find it?</p><p>Two details made the investigation confusing: Xcode could provide paths to build products at launch, and the Debug app contained a file named Library-linking-Test-Xcode-Framework.debug.dylib. They are related to the development workflow, but they solve different problems.</p><p><strong>A build layout tells us where code lives. A launch environment can affect where dependencies are found.</strong> Keeping those questions separate makes this failure much easier to explain.</p><h3>Three things to inspect separately</h3><p><strong>Build layout</strong></p><ul><li><strong>What to inspect: </strong>ENABLE_DEBUG_DYLIB, actual files, symbols</li><li><strong>What it can explain: </strong>Why app code appears in a .debug.dylib</li></ul><p><strong>Packaging</strong></p><ul><li><strong>What to inspect: </strong>Final .app, copy/sign phases</li><li><strong>What it can explain: </strong>Whether a private dynamic framework travels with the app</li></ul><p><strong>Launch context</strong></p><ul><li><strong>What to inspect: </strong>Loaded image paths, relevant DYLD_* variables</li><li><strong>What it can explain: </strong>Why one launch can find a framework that another cannot</li></ul><p>“Debug” and “Release” are configuration names. They usually select different optimization and layout settings, but the names themselves do not define loader behavior. A Release configuration launched from Xcode can still have a development launch environment. A CI job can build a Debug configuration.</p><p>The binary-layout checks below were repeated with <strong>Xcode 26.6 (17F113), Swift 6.3.3, and iOS Simulator builds</strong>. The earlier Xcode-versus-standalone launch observation is the motivation for the troubleshooting procedure; it is not a claim that every Xcode or Simulator version supplies identical environment variables.</p><h3>What @rpath means</h3><p>The app-code image records the framework’s install name:</p><pre>@rpath/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic</pre><p>@rpath is a placeholder for a run-path search. It is not a literal directory and does not mean “look everywhere in DerivedData.”</p><p><strong>@executable_path</strong></p><ul><li><strong>Meaning: </strong>Directory containing the process’s main executable</li></ul><p><strong>@loader_path</strong></p><ul><li><strong>Meaning: </strong>Directory containing the Mach-O image whose load command uses the prefix</li></ul><p><strong>@rpath</strong></p><ul><li><strong>Meaning: </strong>Try the current run-path list, built from LC_RPATH entries along the dependency chain</li></ul><p>For example, an iOS app can record this run path:</p><pre>@executable_path/Frameworks</pre><p>With the framework install name above, that gives a candidate inside the app:</p><pre>MyApp.app/Frameworks/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic</pre><p>An LC_RPATH entry supplies a place to search; it does not copy a missing framework there. See Apple’s <a href="https://github.com/apple-oss-distributions/dyld/blob/main/doc/man/man1/dyld.1">dyld manual</a> for the path substitutions and launch-environment overrides.</p><figure><img alt="Pam and Dwight beside an @rpath reception desk with a directory on a stand and a doorway labeled Frameworks" src="https://cdn-images-1.medium.com/max/1024/1*UmcEP-ELQdIhAnZhsbfvvg.jpeg" /></figure><p><em>A list of places to look is useful only if the required file exists at a reachable location.</em></p><figure><img alt="A framework install name expanded using an app-relative run path, with separate checks for presence and compatibility" src="https://cdn-images-1.medium.com/max/1024/1*cOkshgZLj0Fd2Nk5VaCCxw.png" /></figure><h4>Inspect both the launcher and the app-code image</h4><p>Use the APP, EXECUTABLE, and APP_CODE variables from Part 2, or set them here:</p><pre>APP=&quot;/path/to/Library-linking-Test-Xcode-Framework.app&quot;<br>EXECUTABLE=$(/usr/libexec/PlistBuddy -c &#39;Print :CFBundleExecutable&#39; &quot;$APP/Info.plist&quot;)<br>APP_CODE=&quot;$APP/$EXECUTABLE&quot;<br>if [ -f &quot;$APP/$EXECUTABLE.debug.dylib&quot; ]; then<br>    APP_CODE=&quot;$APP/$EXECUTABLE.debug.dylib&quot;<br>fi<br> <br>xcrun otool -arch arm64 -L &quot;$APP/$EXECUTABLE&quot;<br>xcrun otool -arch arm64 -L &quot;$APP_CODE&quot;<br>xcrun otool -arch arm64 -l &quot;$APP/$EXECUTABLE&quot; | grep -A2 LC_RPATH<br>xcrun otool -arch arm64 -l &quot;$APP_CODE&quot; | grep -A2 LC_RPATH</pre><p>Replace the placeholder path with your build product. Do not stop after inspecting the launcher: the framework dependency may be recorded in the debug dylib.</p><p>In the inspected build, the app-code image has @executable_path/Frameworks among its run paths. That is a bundle-relative path. It is not an injected absolute path to a developer’s build directory.</p><h3>How an Xcode launch can hide a missing embedded framework</h3><p>Consider this deliberately incomplete product:</p><pre>Build/Products/Debug-iphonesimulator/<br>├── XcodeFrameworkDynamic.framework/<br>│   └── XcodeFrameworkDynamic<br>└── MyApp.app/<br>    ├── MyApp<br>    └── MyApp.debug.dylib</pre><p>The framework was built, but it was not copied into MyApp.app/Frameworks. The app can still link because the linker has access to the build products. That says nothing about a later standalone launch.</p><p>In a development launch, DYLD_FRAMEWORK_PATH can supply an additional directory containing the framework. If the process loads that external copy, the app appears to work despite its incomplete bundle. Outside that context, the same app may no longer find the dependency.</p><p>This does not require a different binary, a different configuration, or a .debug.dylib “rescue mechanism.” The decisive difference can be the available search paths and files.</p><h4>Collect evidence in the running app</h4><p>Pause the Xcode-launched app and inspect just the environment keys relevant to this question. Each command below is a single LLDB command:</p><pre>(lldb) expression -l swift -- import Foundation<br>(lldb) expression -l swift -- ProcessInfo.processInfo.environment[&quot;DYLD_FRAMEWORK_PATH&quot;]<br>(lldb) expression -l swift -- ProcessInfo.processInfo.environment[&quot;DYLD_LIBRARY_PATH&quot;]<br>(lldb) image list -f XcodeFrameworkDynamic</pre><p>An environment value only shows a possible search location. The loaded image path is the stronger evidence: did this process use the framework inside the app, or the copy beside it in build products?</p><p>If Swift expression evaluation is unavailable at that stop, inspect the scheme’s launch settings and enable a targeted dyld diagnostic, such as DYLD_PRINT_LIBRARIES=1, for a fresh run. Availability and treatment of DYLD_* variables depend on the platform and process restrictions; do not assume every launch honors them.</p><p>Avoid dumping the entire process environment into a public issue or article. It can contain unrelated credentials and local paths. Share only the relevant keys and replace personal path components.</p><figure><img alt="Michael beside an empty tray in the App office and Dwight beside documents on a separate Build products table" src="https://cdn-images-1.medium.com/max/1024/1*IWqtchQe2kRTfmsq0toEkA.jpeg" /></figure><p><em>The documents are available nearby, but they are still outside the app. A different launch context can expose that omission.</em></p><h4>A controlled reproduction</h4><p>Use the sample app, not a production target, for the missing-framework experiment:</p><ol><li>Keep the dynamic framework linked, but change its embedding option to <strong>Do Not Embed</strong>. Check that another copy phase is not still packaging it.</li><li>Build into a fresh DerivedData directory. Confirm that the framework exists in build products and is absent from the resulting app.</li><li>Run from Xcode. If it launches, inspect the relevant environment values and the loaded framework’s full path. If it fails here too, record that result; the development environment did not hide the omission.</li><li>Stop the app and launch that <strong>same installed build</strong> from the Simulator home screen without rebuilding. Capture the loader error or loaded image path.</li><li>Restore <strong>Embed &amp; Sign</strong>, rebuild, inspect the bundle, and repeat the standalone launch.</li></ol><p>Keep the configuration, Simulator runtime, and artifact fixed while comparing the two launch contexts. Switching Debug to Release at the same time changes several variables and weakens the diagnosis.</p><p>For a required launch-time dependency, a missing image can stop the process before the app reaches its entry point. A missing symbol, incompatible architecture, wrong platform slice, or invalid signature can produce a different loader failure. Read the full error, especially Referenced from and the attempted paths. Weak linking and libraries opened later with dlopen are separate cases.</p><h4>A repeatable check with an explicit search path</h4><p>I also checked the loader behavior on an isolated <strong>iPhone 16 Simulator running iOS 26.5</strong>, using the same Debug executable and debug dylib throughout. For the incomplete case, I removed the dynamic framework from a disposable copy of the built app, then installed that copy.</p><p><strong>Framework embedded</strong></p><ul><li><strong>Additional framework search path: </strong>None supplied by the test</li><li><strong>Result: </strong>Both math functions ran</li></ul><p><strong>Framework missing</strong></p><ul><li><strong>Additional framework search path: </strong>None supplied by the test</li><li><strong>Result: </strong>Library not loaded; neither math function ran</li></ul><p><strong>The same incomplete bundle</strong></p><ul><li><strong>Additional framework search path: </strong>Build products directory supplied explicitly</li><li><strong>Result: </strong>Both math functions ran</li></ul><p>The app-code file’s SHA-256 was identical across these cases. The successful processes remained running until the test stopped them; this was a launch check, not a performance benchmark.</p><p>For the third case, simctl can pass the override to the launched process:</p><pre>SIMCTL_CHILD_DYLD_FRAMEWORK_PATH=&quot;$BUILD_PRODUCTS&quot; \<br>  xcrun simctl launch --terminate-running-process &quot;$SIMULATOR_UDID&quot; &quot;$BUNDLE_ID&quot;</pre><p>Set the three variables to your build-products directory, test Simulator identifier, and app bundle identifier. Install the test app first. The SIMCTL_CHILD_ prefix is how this command supplies DYLD_FRAMEWORK_PATH to the child process.</p><p>This checks the effect of an explicit search path. It does <strong>not</strong> establish which variables a particular Xcode scheme supplies automatically; inspect that launch separately using the earlier steps. Keep the experiment on a disposable Simulator build, and restore normal embedding afterward.</p><h3>What App.debug.dylib actually contains</h3><p>In Xcode’s debug dylib layout, the executable is a small entry point and the app’s linked code lives in a companion dynamic library. This supports the shared build product used by normal runs and Previews.</p><p>Apple documents the default conditions for ENABLE_DEBUG_DYLIB: a bundled executable target, SWIFT_VERSION set, and SWIFT_OPTIMIZATION_LEVEL=-Onone. The setting is target-specific; it is not a universal property of every Debug build. See <a href="https://developer.apple.com/documentation/xcode/understanding-build-product-layout-changes">Understanding build product layout changes in Xcode</a>.</p><p>A .debug.dylib contains executable code. It is not simply a bag of debug symbols, and it is not interchangeable with a .dSYM.</p><p>Here is the layout of the sample with debug dylib support enabled:</p><pre>MyApp.app/<br>├── MyApp                              small launcher<br>├── MyApp.debug.dylib                  app code + linked static library code<br>└── Frameworks/<br>    └── XcodeFrameworkDynamic.framework/<br>        └── XcodeFrameworkDynamic     separate dynamic implementation</pre><p>With that support disabled, the app and static library code can instead live in MyApp:</p><pre>MyApp.app/<br>├── MyApp                              app code + linked static library code<br>└── Frameworks/<br>    └── XcodeFrameworkDynamic.framework/<br>        └── XcodeFrameworkDynamic     still a separate implementation</pre><figure><img alt="The same static code linked into a debug dylib or main executable, while the dynamic framework remains a separate image in both layouts" src="https://cdn-images-1.medium.com/max/1024/1*jamKo8MgIyLbdP2Oq8VBHw.png" /></figure><p><strong>The static library remains statically linked in both layouts.</strong> The output image changed; the library did not become a separately loaded framework.</p><figure><img alt="A small App reception desk leading to an office labeled App.debug.dylib" src="https://cdn-images-1.medium.com/max/1024/1*f-F-GzH3qG8kg_JVwEzwHA.jpeg" /></figure><p><em>The entrance is small; the work happens in the other room. Statically linked code can live in that room too.</em></p><h4>Verify the layout instead of guessing from the configuration name</h4><p>For the sample project, inspect its effective settings:</p><pre>xcodebuild \<br>  -project Library-linking-Test-Xcode-Framework.xcodeproj \<br>  -scheme Debug \<br>  -configuration Debug \<br>  -sdk iphonesimulator \<br>  -showBuildSettings \<br>  | grep -E &#39;ENABLE_DEBUG_DYLIB|SWIFT_OPTIMIZATION_LEVEL|LD_RUNPATH_SEARCH_PATHS&#39;</pre><p>The command can print settings for more than one target. Check the app target’s section when interpreting them. Replace the project and scheme names for your own app.</p><p>For a controlled comparison, build the app with its usual settings, then build again with ENABLE_DEBUG_DYLIB=NO. Use separate output directories so an old dylib cannot confuse the result. This changes layout; it does not fix a missing embedded framework.</p><p>The three sample builds inspected during this revision produced:</p><p><strong>Debug, default layout</strong></p><ul><li><strong>Image containing the static </strong><strong>MyMathStatic.add definition: </strong>App.debug.dylib</li><li><strong>Dynamic dependency: </strong>Separate framework</li></ul><p><strong>Debug, </strong><strong>ENABLE_DEBUG_DYLIB=NO</strong></p><ul><li><strong>Image containing the static </strong><strong>MyMathStatic.add definition: </strong>App</li><li><strong>Dynamic dependency: </strong>Separate framework</li></ul><p><strong>Release, sample defaults</strong></p><ul><li><strong>Image containing the static </strong><strong>MyMathStatic.add definition: </strong>App</li><li><strong>Dynamic dependency: </strong>Separate framework</li></ul><p>These are results for this project and toolchain, not rules inferred from the words “Debug” and “Release.”</p><h3>Why this matters for CI and distribution</h3><p>A CI build completing successfully proves that the build completed. An archive completing successfully proves that an archive was created. Neither result alone proves that every shipped process will load every required private framework.</p><p>For an iOS app, inspect the actual artifact you intend to distribute:</p><ol><li>Locate the app under Products/Applications in the archive, or under Payload in an extracted IPA.</li><li>Inspect the executable’s recorded dependencies and run paths. Repeat for embedded dynamic frameworks and app extensions, including their transitive dependencies.</li><li>Confirm that required private dynamic frameworks are packaged at reachable locations with the correct device platform, architecture, and signing. System frameworks are supplied by the OS.</li><li>Launch the exported app through the appropriate device distribution route, without relying on Xcode’s build-products directory. Exercise extension entry points too.</li></ol><p>Do not “fix” distribution by adding an absolute path to your local build directory. That directory will not exist on a user’s device. Fix the dependency graph, copying/signing configuration, or the relative run paths in the product.</p><p>Apple’s <a href="https://developer.apple.com/library/archive/technotes/tn2435/_index.html">framework embedding troubleshooting guide</a> is useful for missing, incompatible, and incorrectly packaged framework errors. Its older UI screenshots should be read alongside the build phases in your current Xcode version.</p><h3>Does choosing static linking avoid this problem?</h3><p>It removes one specific requirement: there is no separate runtime file for that static archive that dyld must find. It does not remove the app’s other dynamic dependencies or copy its resources automatically.</p><p>For this series, I would use the following diagnostic order:</p><ul><li><strong>Where is the implementation?</strong> Find its owning image.</li><li><strong>What does that image require?</strong> Read the load commands.</li><li><strong>What did we ship?</strong> Inspect the final bundle.</li><li><strong>What actually loaded?</strong> Check the process and its launch context.</li></ul><p>That sequence explains both the direct-versus-stub call in Part 2 and the app that works only from Xcode. It also gives us something more useful than “Debug is forgiving”: a specific file, dependency, or path to correct.</p><p>Originally published at <a href="https://dementievmykola.com/blog/static_vs_dynamic_frameworks_dispatching/article_-_3_-_debug_vs_release_-_rpath_and_the_debug_dylib/">dementievmykola.com</a> on October 4, 2026.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3d29ab495d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static vs Dynamic Framework Dispatching (Part 2 of 3): SPM vs Xcode frameworks]]></title>
            <link>https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-2-of-3-spm-vs-xcode-frameworks-94b3fbded041?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/94b3fbded041</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 09:01:36 GMT</pubDate>
            <atom:updated>2026-10-04T19:33:10.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Hands-on experiments with static and dynamic frameworks, part 2 of 3" src="https://cdn-images-1.medium.com/max/1024/1*tcnpVHQqctWkw_h8CNw6NQ.jpeg" /></figure><p>This is Part 2 of a three-part series:</p><ul><li><a href="https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-1-of-3-dispatching-under-the-hood-01a4f5996342">Part 1: Dispatching under the hood</a></li><li><strong>Part 2: Hands-on experiments with SPM and Xcode frameworks</strong></li><li>Part 3: <a href="https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-3-of-3-debug-release-rpath-and-the-debug-dylib-0f3d29ab495d">Debug, Release, @rpath, and the debug dylib</a> (4 October 2026)</li></ul><p>In Part 1, we followed a call from the app into library code. Now I want to find that call in a compiled app. Where did the static implementation end up? Which image owns the dynamic implementation? And what can a terminal command actually prove?</p><p>The examples use two small apps: one with Xcode framework targets, another with Swift Package Manager products. Both call an add function from a static library and a dynamic library. The arithmetic is deliberately boring. The interesting part is everything around the call.</p><h3>What we will check</h3><p><strong>Is this library an archive or a dynamic Mach-O image?</strong></p><ul><li><strong>Useful evidence: </strong>file, otool -hv</li></ul><p><strong>Which image defines the function?</strong></p><ul><li><strong>Useful evidence: </strong>nm, with demangled names</li></ul><p><strong>What dynamic dependencies does this image record?</strong></p><ul><li><strong>Useful evidence: </strong>otool -L, otool -l</li></ul><p><strong>Does this particular call branch to local code or a symbol stub?</strong></p><ul><li><strong>Useful evidence: </strong>Disassembly of the <strong>caller</strong></li></ul><p><strong>Which imported symbol does a pointer slot refer to?</strong></p><ul><li><strong>Useful evidence: </strong>dyld_info -imports -fixups</li></ul><p><strong>Which images did this process actually load?</strong></p><ul><li><strong>Useful evidence: </strong>LLDB image list</li></ul><p>One distinction will matter throughout: <strong>static versus dynamic linking is separate from Swift or Objective-C method dispatch</strong>. A statically linked library can still use protocol witness tables, class dispatch, closures, and Objective-C messaging. Here we inspect specific calls to simple functions, not every possible call a library can make.</p><h3>Set up the experiment</h3><p>The two projects use these names:</p><p><strong>Xcode targets</strong></p><ul><li><strong>App: </strong>Library-linking-Test-Xcode-Framework</li><li><strong>Static dependency: </strong>XcodeFrameworkStatic</li><li><strong>Dynamic dependency: </strong>XcodeFrameworkDynamic</li></ul><p><strong>SwiftPM products</strong></p><ul><li><strong>App: </strong>Library-linking-Test</li><li><strong>Static dependency: </strong>SDK-SPM-Static</li><li><strong>Dynamic dependency: </strong>SDK-SPM-Dynamic</li></ul><p>The Xcode libraries expose MyMathStatic.add and MyMathDynamic.add. The SwiftPM modules both expose MyMath.add, so the app qualifies calls with SDK_SPM_Static or SDK_SPM_Dynamic. Some implementations also print a message, which makes them easier to find and confirms execution.</p><p>This is the essential API shape, with the logging omitted:</p><pre>public struct MyMathStatic {<br>    public static func add(_ a: Int, _ b: Int) -&gt; Int {<br>        a + b<br>    }<br>}</pre><p>To recreate the Xcode case, start with an iOS app and add two framework targets with the names above. Put the static API in one target and the equivalent MyMathDynamic API in the other. Set their Mach-O types as shown below, link both to the app, and call both functions from the app so the linker has a reason to include them:</p><pre>import XcodeFrameworkStatic<br>import XcodeFrameworkDynamic<br> <br>print(MyMathStatic.add(2, 4))<br>print(MyMathDynamic.add(2, 4))</pre><p>Place those calls in an app lifecycle callback, such as the sample view’s onAppear. This recreates the linkage relationship; addresses and incidental runtime imports will differ from my build.</p><p>Use an unoptimized build for the first inspection. Optimization, inlining, dead stripping, and symbol stripping can change or remove the evidence we are looking for. An absent symbol in nm is not, by itself, proof that code was never linked.</p><p>The Xcode binary excerpts below were rechecked with <strong>Xcode 26.6 (17F113), Swift 6.3.3, and the arm64 iOS Simulator slice</strong>. Addresses are specific to that build. Earlier screenshots show the setup, not an exact promise about current Xcode’s UI or output.</p><figure><img alt="LEGO office characters gathered around a microscope and computer to inspect their experiment" src="https://cdn-images-1.medium.com/max/1024/1*EiLWVZIkuS0XbTVq_ghpJg.jpeg" /></figure><p><em>Time to inspect the product. The build setting tells us what we asked for; the binary tells us what we got.</em></p><h4>Xcode framework targets</h4><p>For these sample targets, <strong>Mach-O Type</strong> is Static Library for XcodeFrameworkStatic and Dynamic Library for XcodeFrameworkDynamic.</p><figure><img alt="Xcode build settings for the static framework target" src="https://cdn-images-1.medium.com/max/1024/1*cMktmi1CHIPx_-tBkXHLSg.png" /></figure><figure><img alt="Xcode build settings for the dynamic framework target" src="https://cdn-images-1.medium.com/max/1024/1*YrZVpNbGWhZKmDZloi6aSw.png" /></figure><p>The .framework suffix is a bundle format. It does not, on its own, prove that the binary inside is dynamic. Inspect that binary:</p><pre>file &quot;$BUILD_PRODUCTS/XcodeFrameworkStatic.framework/XcodeFrameworkStatic&quot;<br>file &quot;$BUILD_PRODUCTS/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic&quot;</pre><p>Set BUILD_PRODUCTS to your build’s products directory first. In this experiment, the static result is an archive, while the dynamic result is a dynamically linked shared library. A universal build can report more than one architecture.</p><h4>Swift Package Manager products</h4><p>The sample manifests explicitly choose a linkage type:</p><pre>.library(<br>    name: &quot;SDK-SPM-Static&quot;,<br>    type: .static,<br>    targets: [&quot;SDK-SPM-Static&quot;]<br>)</pre><pre>.library(<br>    name: &quot;SDK-SPM-Dynamic&quot;,<br>    type: .dynamic,<br>    targets: [&quot;SDK-SPM-Dynamic&quot;]<br>)</pre><p>These are product declarations, not complete manifests. The corresponding targets and source paths must also exist. If a product leaves type unspecified, SwiftPM lets the consumer choose the linkage; do not read an omitted type as an explicit .static declaration. See the <a href="https://docs.swift.org/package-manager/PackageDescription/PackageDescription.html">SwiftPM product API</a>.</p><p>Xcode’s SwiftPM integration can package a dynamic product as a framework. A command-line SwiftPM build can produce a .dylib. Inspect the product generated by the tool you actually used, rather than assuming its extension from Package.swift.</p><p>The SwiftPM app was also rebuilt for this revision. Its app-code image defines the static MyMath.add and imports the dynamic one:</p><pre>T _$s14SDK_SPM_Static6MyMathV3addyS2i_SitFZ<br>U _$s15SDK_SPM_Dynamic6MyMathV3addyS2i_SitFZ</pre><p>Addresses are omitted here. otool -L records @rpath/SDK-SPM-Dynamic.framework/SDK-SPM-Dynamic. In this sample configuration, that framework was not embedded in the app, so a successful build alone was not enough to make the product ready for standalone launch. The next section explains the missing step.</p><figure><img alt="Jim and Dwight sharing one desk labeled Static, with Pam and Michael at separate desks labeled Dynamic" src="https://cdn-images-1.medium.com/max/1024/1*ub12R1J-EYyvr7WWRPSW1g.jpeg" /></figure><p><em>One shared workspace versus separate workspaces: a metaphor for where the implementations live, not for how fast they run.</em></p><h3>Linking and embedding are separate steps</h3><p><strong>Linking</strong> connects code and records dependencies. <strong>Embedding</strong> puts a runtime dependency into the app bundle. A successful link does not guarantee that the app contains everything it needs at launch.</p><p>In the Xcode-framework sample, the app target uses <strong>Embed &amp; Sign</strong> for its own dynamic framework. For its static framework, it uses <strong>Do Not Embed</strong>: the archive is an input to the linker, not a runtime image to ship beside the executable.</p><figure><img alt="Xcode’s framework linking and embedding settings for the sample app" src="https://cdn-images-1.medium.com/max/1024/1*u81vcRIu9bSUAoVEuTcOOQ.png" /></figure><p>This is not a rule that every entry marked “Do Not Embed” must be static. Apple system frameworks are dynamic and are supplied by the operating system. Package managers may also arrange copying and signing through generated build phases. Check the final bundle as well as the settings screen. Apple’s <a href="https://developer.apple.com/library/archive/technotes/tn2435/_index.html">framework embedding guide</a> explains the distinction and common missing-framework failures.</p><p>Resources are another separate concern. Statically linking code does not automatically copy every image, localization, or resource bundle that code needs.</p><figure><img alt="Pam and Michael beside an open case labeled App bundle, with documents resting inside it" src="https://cdn-images-1.medium.com/max/1024/1*Bm8d-RBjwmzDjMuMTH9hsw.jpeg" /></figure><p><em>Linking records a dependency. Embedding makes sure the runtime file travels with the app.</em></p><h3>Find the image that contains the app code</h3><p>Before running nm, identify the right file. In a build with Xcode’s debug dylib support, the app executable is a small launcher and most app code is in App.debug.dylib. That includes code statically linked from our sample library.</p><p>For this iOS app, set APP to the built .app directory, then run:</p><pre>APP=&quot;/path/to/Library-linking-Test-Xcode-Framework.app&quot;<br>EXECUTABLE=$(/usr/libexec/PlistBuddy -c &#39;Print :CFBundleExecutable&#39; &quot;$APP/Info.plist&quot;)<br>APP_CODE=&quot;$APP/$EXECUTABLE&quot;<br> <br>if [ -f &quot;$APP/$EXECUTABLE.debug.dylib&quot; ]; then<br>    APP_CODE=&quot;$APP/$EXECUTABLE.debug.dylib&quot;<br>fi<br> <br>DYNAMIC_CODE=&quot;$APP/Frameworks/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic&quot;</pre><p>The path is a placeholder; replace it with your own build product. This layout is specific to the iOS sample. A macOS app has a different bundle structure.</p><p>Selecting the debug dylib does not mean the static framework became a dynamic dependency. It means a different output image received the statically linked code. <a href="https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-3-of-3-debug-release-rpath-and-the-debug-dylib-0f3d29ab495d">Part 3</a> examines that layout in detail.</p><h3>Experiment 1: find the definitions and imports</h3><pre>xcrun nm -arch arm64 &quot;$APP_CODE&quot; | grep MyMath | xcrun swift-demangle<br>xcrun nm -arch arm64 &quot;$DYNAMIC_CODE&quot; | grep MyMath | xcrun swift-demangle</pre><p>In the app-code image, the relevant un-demangled lines from the inspected Debug build are:</p><pre>0000000000004188 T _$s20XcodeFrameworkStatic06MyMathC0V3addyS2i_SitFZ<br>                 U _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ</pre><p>T identifies a text-section definition in this image. U identifies an undefined symbol that this image imports. The dynamic framework’s binary supplies the second definition.</p><p>So we have two different relationships:</p><ul><li>The static library contributed code to APP_CODE; it has no separate runtime image of its own.</li><li>APP_CODE imports the dynamic function from another Mach-O image.</li></ul><p>This is a useful result for this build. With optimized or stripped products, combine symbol inspection with dependency information, a linker map, or matching debug symbols before drawing the same conclusion.</p><h3>Experiment 2: inspect recorded dependencies</h3><pre>xcrun otool -arch arm64 -L &quot;$APP_CODE&quot;<br>xcrun otool -arch arm64 -L &quot;$DYNAMIC_CODE&quot;</pre><p>The relevant dependency recorded in the app-code image is:</p><pre>@rpath/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic</pre><p>There is no equivalent load command for XcodeFrameworkStatic. Its selected code was linked into the output image.</p><p>Two details prevent misleading readings of this output:</p><ol><li>otool -L reads the file. It does <strong>not</strong> list all images loaded by a running process, nor does it recursively expand every dependency.</li><li>For a dylib, it also displays that dylib’s own install name, from LC_ID_DYLIB. The App.debug.dylib line in its own output is its identity, not a dependency on another copy of itself. Use otool -D for the identity or otool -l to distinguish load-command types.</li></ol><h3>Experiment 3: follow the call instruction</h3><p>Inspect the <strong>caller</strong>, where the call sites and imported-symbol stubs live:</p><pre>xcrun otool -arch arm64 -tvV &quot;$APP_CODE&quot; | grep -A6 addyS2i_SitFZ</pre><p>Relevant lines from the same build:</p><pre>00000000000015dc bl 0x4b38 ; symbol stub for: _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ<br>0000000000001748 bl _$s20XcodeFrameworkStatic06MyMathC0V3addyS2i_SitFZ</pre><p>Both use bl, the arm64 branch-and-link instruction. The difference is the <strong>destination</strong>. One branches to an imported-symbol stub; the other branches to the static function’s implementation within this image.</p><p>The first line is a call <strong>to</strong> a stub, not the stub body itself. To examine the stub instructions and pointer sections, use:</p><pre>xcrun dyld_info -arch arm64 -disassemble &quot;$APP_CODE&quot;<br>xcrun otool -arch arm64 -Iv &quot;$APP_CODE&quot;</pre><figure><img alt="Static code linked into the app-code image, compared with an imported dynamic function reached through a stub and pointer" src="https://cdn-images-1.medium.com/max/1024/1*T5R3HqBIJPl8BIqh6CIM9A.png" /></figure><p>This sample demonstrates a direct call to the static implementation. It does not establish “static linking means zero indirection everywhere.” Compiler optimization, language dispatch, function pointers, and other dynamic dependencies remain relevant.</p><h3>A GOT entry does not prove lazy binding</h3><p>This is where a binary dump can tempt us into claiming too much. Finding __stubs and __got establishes indirection. It does not establish that the function’s address is resolved on its first call.</p><p>Inspect the actual imports and fixups:</p><pre>xcrun dyld_info -arch arm64 -imports -fixups &quot;$APP_CODE&quot; | grep MyMath<br>xcrun otool -arch arm64 -l &quot;$APP_CODE&quot; | grep -A3 LC_DYLD_CHAINED_FIXUPS</pre><p>For the inspected binary, dyld_info associates a slot in __DATA_CONST,__got with XcodeFrameworkDynamic.MyMathDynamic.add, and the load commands include LC_DYLD_CHAINED_FIXUPS.</p><p>Modern chained fixups describe pointers that need binding or rebasing. Their on-disk bytes can encode fixup information; they are not necessarily the final pointers a running process sees. A raw hex dump of __got cannot demonstrate a before-and-after first call.</p><p>Classic lazy binding is a different case: an unresolved call takes a resolver path, then later calls use the resolved pointer. Do not substitute that model for every modern stub. Apple discusses chained fixups and page-in linking in <a href="https://developer.apple.com/videos/play/wwdc2022/110362/">Link fast: Improve build and launch times</a>. Page-in linking concerns memory pages becoming available, not a promise to resolve each function at its first call.</p><p>Also avoid counting __got sections as a static/dynamic test. Even an app using only our static math library imports system and Swift runtime functions, so its final image can contain both stubs and a GOT.</p><h3>Experiment 4: check the running process</h3><p>Pause the app in Xcode’s debugger, then use LLDB:</p><pre>(lldb) image list<br>(lldb) image lookup -rn &#39;MyMathStatic.*add&#39;<br>(lldb) image lookup -rn &#39;MyMathDynamic.*add&#39;</pre><p>Look at the owning image and its path. In a build with debug dylib support, expect the static implementation in the app’s debug dylib and the dynamic implementation in its framework image. Without that support, the static implementation can be in the main executable instead.</p><p>Image indices and addresses vary. An index such as [22] in someone else’s capture is not a rule about where app code belongs. If a lookup fails, check optimization and available symbols before interpreting it as missing code.</p><p>The image path also tells you <strong>which copy</strong> of a framework loaded. A copy in the build products directory and a copy inside the installed app can have the same name. That distinction will drive the missing-framework experiment in Part 3.</p><h3>Where CocoaPods fits</h3><p>CocoaPods can choose how source dependencies are built and packaged:</p><pre>use_frameworks! :linkage =&gt; :static<br># Or, in an alternative configuration:<br># use_frameworks! :linkage =&gt; :dynamic</pre><p>The <a href="https://guides.cocoapods.org/syntax/podfile">Podfile reference</a> documents these linkage options. A vendored precompiled binary still has its own linkage type; a Podfile setting cannot turn an existing dynamic binary into a static archive. Inspect the resulting binary using the same commands.</p><h3>What these experiments say about performance</h3><p>Static linking can reduce the number of separately loaded private images. Dynamic linking keeps a dependency in its own image and may avoid duplicating shared code across several consumers in one process. Neither observation gives us a launch-time measurement.</p><p>The linker can extract selected archive members, dead-strip unused sections, and cooperate with compiler optimizations. It does not necessarily copy every function from a static library into the app. Conversely, moving code into a dynamic framework can shrink the main executable while leaving total app size unchanged or larger.</p><p>Compare the final app bundle or exported artifact, not just one executable. Use size for segment sizes, not as a substitute for download size or resident memory. For launch performance, measure equivalent optimized builds on a device with Instruments and repeated runs.</p><h3>What we established</h3><p>For the sample’s inspected calls, static code belongs to the app-code image, while the dynamic function remains an import supplied by a separate framework. Xcode targets and SwiftPM products lead to the same questions about the final binary: where is the definition, what dependency is recorded, and where does the call go?</p><p>The next problem is more deceptive: <strong>what if the binary records the right dependency, the framework is missing from the app, and an Xcode run still succeeds?</strong> In <a href="https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-3-of-3-debug-release-rpath-and-the-debug-dylib-0f3d29ab495d">Part 3</a>, we separate build layout from launch environment and investigate exactly that case.</p><p>Originally published at <a href="https://dementievmykola.com/blog/static_vs_dynamic_frameworks_dispatching/article_-_2_-_hands_-_on_experiments_with_spm_and_xcode_frameworks/">dementievmykola.com</a> on October 3, 2026.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94b3fbded041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Subtitle Pipeline for 106 TV Episodes with Whisper, Groq, and Python]]></title>
            <link>https://medium.com/@mykola.dementiev/how-i-built-a-subtitle-pipeline-for-106-tv-episodes-with-whisper-groq-and-python-b8565f779a97?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8565f779a97</guid>
            <category><![CDATA[groq]]></category>
            <category><![CDATA[subtitles]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[whisper]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 00:00:33 GMT</pubDate>
            <atom:updated>2026-09-30T12:13:07.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*NHeShRk7gAHzDuSq.jpg" /></figure><h3>TL;DR</h3><ul><li>Whisper creates missing source subtitles before translation. I started with a self-hosted server and now use Groq-hosted Whisper, which was faster on my setup.</li><li>translate_subtitles.py searches OpenSubtitles for Ukrainian subtitles first. It can correct a constant timing offset and uniform drift when the releases match.</li><li>TRANSLATOR_CHAIN sets the order of Google, MyMemory, LibreTranslate, Argos, and Claude CLI, including retries and timeout increases. Only unresolved cues move to the next step.</li><li>Each run skips existing outputs and logs its progress. The default acceptance threshold is 60 percent cue coverage, so a saved file can still contain English dialogue.</li></ul><h3>The job was bigger than translation</h3><p>I had 106 episodes of <em>The Fosters</em> in .mkv format. Some came with an English .srt, some had no subtitle file at all, and a few had Ukrainian subtitles timed for a different release. I wanted one repeatable workflow that could handle all three cases without throwing away completed work.</p><p>That meant separating two jobs that are easy to blur together:</p><ol><li>Create a source-language SRT from the episode audio when no usable source subtitle exists.</li><li>Produce the target-language SRT by finding, synchronizing, or translating subtitles.</li></ol><p>translate_subtitles.py handles the second job. It does not invoke Whisper itself. The complete workflow uses a transcription helper first, then feeds the generated English SRT into the translation pipeline.</p><p>The obvious loop was not enough:</p><pre>for line in subtitles:<br>    translated = translator.translate(line)</pre><p>That loop says nothing about:</p><ul><li>creating timed source cues from audio when the episode has no SRT;</li><li>finding an existing Ukrainian file before paying any translation cost;</li><li>rejecting files mislabeled as Ukrainian;</li><li>matching subtitle timing to a different release;</li><li>falling back when a translator returns an empty or non-Cyrillic result;</li><li>preserving progress across several runs.</li></ul><p>The first missing stage was speech-to-text.</p><h3>Stage 1: create the source SRT from audio</h3><p>My first batch route ran <a href="https://github.com/ahmetoner/whisper-asr-webservice">whisper-asr-webservice</a> on a server. The client connects over SSH, finds video files recursively, skips any video that already has a sibling SRT, and posts the rest to the server’s /asr endpoint.</p><pre>export WHISPER_ASR_HOST=&quot;server.example.net&quot;<br>export WHISPER_ASR_USER=&quot;media&quot;<br>export WHISPER_ASR_SSH_KEY=&quot;$HOME/.ssh/id_whisper&quot;<br>export WHISPER_LANGUAGE=&quot;en&quot;<br>./whisper_batch.sh &quot;/srv/media/The Fosters&quot;</pre><p>The self-hosted route had no per-request API fee, but it was slow on my hardware and its transcripts needed more correction than I wanted. I kept the script as an offline option, not as my default.</p><p>My current route is transcribe-groq.py. It extracts 16 kHz mono audio with FFmpeg, compresses it to Ogg Opus, splits long recordings into 25-minute chunks, calls <a href="https://console.groq.com/docs/speech-to-text">Groq’s Whisper transcription endpoint</a>, restores absolute timestamps, validates segment text and timing, and writes one SRT atomically. It preserves repeated dialogue and phrases that might be mistaken for hallucinations; those need human review. Existing output is protected unless I pass --force, and even then an empty or malformed result leaves the previous SRT intact.</p><pre>export GROQ_API_KEY=&quot;your-api-key&quot;<br>python3 transcribe-groq.py \<br>  &quot;The Fosters S01E01.mkv&quot; \<br>  --language en \<br>  --prompt &quot;Character names: Lena, Stef, Callie, Jude&quot;</pre><p>The prompt is optional. I use it only for names and terms Whisper is likely to miss. The published version contains no personal prompt, local path, server address, login, or API key.</p><p>Both helpers are available beside the main script:</p><ul><li><a href="https://dementievmykola.com/blog/make_subtitles_translation/transcribe-groq.py">Download the Groq transcription script</a></li><li><a href="https://dementievmykola.com/blog/make_subtitles_translation/whisper_batch.sh">Download the self-hosted Whisper batch script</a></li></ul><p>Neither route makes the source transcript correct by definition. Names, music captions, overlapping dialogue, and cuts at chunk boundaries still deserve a spot check before translation.</p><p>Groq receives the audio chunks. Google, MyMemory, and Claude receive subtitle text when their turn in the chain is reached; OpenSubtitles receives search metadata and authentication details for its own API. For private material, choose services whose data policies suit the content, or use self-hosted transcription and offline translation.</p><p>Once a source SRT exists, the rest of the workflow can make one decision per episode instead of one decision per cue.</p><h3>The pipeline</h3><p>For each episode, the two-stage workflow follows this order:</p><ol><li>Skip the episode if a .uk.srt output already exists.</li><li>Create an English SRT from audio if no source subtitle exists.</li><li>Search OpenSubtitles for a Ukrainian candidate.</li><li>Reject candidates that fail basic language and structure checks.</li><li>Fit a linear timing transform against the local English file.</li><li>If no candidate survives, translate unique subtitle phrases through the fallback chain.</li><li>Write the result and update both the structured run log and console log.</li></ol><figure><img alt="Subtitle pipeline: create source subtitles, search and synchronize a Ukrainian candidate, then translate unresolved cues through a fallback chain." src="https://cdn-images-1.medium.com/max/1024/1*CRrcWheW53rYSHh7laz7Eg.png" /></figure><p>Finding a valid existing subtitle ends the job before any translator is called.</p><h3>Search before translation</h3><p>The script queries the <a href="https://opensubtitles.tawk.help/article/about-the-api">OpenSubtitles API</a> with the parsed series title, season number, episode number, and the configured target-language code. With the included preset, TARGET_LANGUAGE_CODE resolves to uk.</p><pre>data = _os_get(&quot;/subtitles&quot;, {<br>    &quot;query&quot;: title,<br>    &quot;season_number&quot;: season,<br>    &quot;episode_number&quot;: episode,<br>    &quot;languages&quot;: TARGET_LANGUAGE_CODE,<br>})</pre><p>OpenSubtitles quotas depend on the account and API consumer, so the local ceiling is configurable. The downloadable script defaults to 20. That value is configuration, not a promise: set OPENSUBTITLES_DAILY_LIMIT to the limit shown for your own account.</p><p>Credentials also belong outside the file:</p><pre>OPENSUBTITLES_API_KEY      = os.environ.get(&quot;OPENSUBTITLES_API_KEY&quot;, &quot;&quot;)<br>OPENSUBTITLES_ACCESS_TOKEN = os.environ.get(&quot;OPENSUBTITLES_ACCESS_TOKEN&quot;, &quot;&quot;)<br>OPENSUBTITLES_USERNAME     = os.environ.get(&quot;OPENSUBTITLES_USERNAME&quot;, &quot;&quot;)<br>OPENSUBTITLES_PASSWORD     = os.environ.get(&quot;OPENSUBTITLES_PASSWORD&quot;, &quot;&quot;)<br>OS_DAILY_LIMIT = int(os.environ.get(&quot;OPENSUBTITLES_DAILY_LIMIT&quot;, &quot;20&quot;))</pre><p>The script sends an API key for search and requires an authenticated session for its download path. That is a policy of this script: <a href="https://opensubtitles.tawk.help/article/getting-started">OpenSubtitles also documents a limited anonymous allowance</a>. The script accepts OPENSUBTITLES_ACCESS_TOKEN directly or obtains a session token from the username and password at startup. It does not intentionally log credentials; review logs before sharing them.</p><p>Search results are not trusted just because their metadata says uk. The script samples the first 50 cues, checks that the text is mostly Cyrillic, and looks for Ukrainian-specific characters such as і, ї, є, and ґ. Russian-only characters such as ы, э, and ъ count against the candidate.</p><p>The guard now applies to actual /download attempts, not only accepted subtitles. A rejected candidate can still consume API quota, so every attempted download reduces the remaining local budget. Once it reaches zero, the script skips OpenSubtitles and continues with the translation chain.</p><p>Short samples, names, songs, and mixed-language dialogue can fool this filter. It does one useful job: it rejects many obviously mislabeled files before they reach the output directory. It does not prove that the remaining text is Ukrainian.</p><p>Once a candidate passes that check, timing becomes the next failure point.</p><h3>Two points can fix drift, but not editing</h3><p>Subtitle releases often disagree by a fixed start offset. Some also drift because the video was encoded at a different frame rate. A linear transform handles both effects:</p><pre>new_time = scale * old_time + offset</pre><p>The script takes the first and last cue start times from the local English file and the downloaded Ukrainian file:</p><pre>scale = (en_t1 - en_t0) / (uk_t1 - uk_t0)<br>offset = en_t0 - scale * uk_t0</pre><p>It then rejects suspicious matches:</p><ul><li>the cue counts may differ by no more than 20 percent;</li><li>scale must stay within 10 percent of 1.0;</li><li>the first five transformed cue starts must remain within two seconds of their English counterparts.</li></ul><figure><img alt="Two-point subtitle timing calibration using the first and last cues to correct offset and uniform drift." src="https://cdn-images-1.medium.com/max/1024/1*-gbdKSUI2weCzqhBPvk5rg.png" /></figure><figure><img alt="Two LEGO film strips aligned with first and last calibration markers." src="https://cdn-images-1.medium.com/proxy/0*6riDttzapJAVhntr.jpg" /></figure><p>This works when the first and last cues refer to the same moments and the mismatch is approximately linear. It fails when one release adds a recap, removes captions, splits dialogue differently, or inserts an extra scene. A stronger synchronizer would match cue content or audio landmarks instead of assuming correspondence by index.</p><p>When no compatible Ukrainian file exists, the pipeline finally translates.</p><h3>A configurable Chain of Responsibility</h3><p>The chain is configured at the top of the script:</p><pre>TRANSLATOR_CHAIN = (<br>    &quot;Google (2:30) -&gt; MyMemory (1:10) -&gt; &quot;<br>    &quot;LibreTranslate (1:20) -&gt; Argos -&gt; Claude&quot;<br>)</pre><p>Any registered service can move to any position in TRANSLATOR_CHAIN. The parser skips unavailable services and uses the first remaining service for the primary batch. The linked fallback chain follows the same order.</p><p>“Available” is deliberately a local setup check, not a live health check. The script verifies that the required Python package, Argos language model, LibreTranslate URL, or claude executable exists. A configured service can still time out later, which is why runtime failures continue through the same chain.</p><p>For example, I can switch to an offline-first setup without changing translate_file():</p><pre>TRANSLATOR_CHAIN = &quot;Argos -&gt; Google (3:20) -&gt; Claude&quot;</pre><p>Argos receives the primary batch in this configuration. The settings move with each service: Google (3:20) means one attempt plus three retries, with 20 seconds added to the timeout for each retry. A service without parentheses gets one attempt and no retry.</p><p>For the primary service, the batch pass is that first attempt. If its configuration says Google (2:30), failed cues get two more Google attempts at 60 and 90 seconds before moving to MyMemory. The primary service is not repeated at the base timeout when the linked chain begins.</p><p>The timeout applies per Google chunk of up to 20 cues, per MyMemory chunk of up to 5 cues, per LibreTranslate HTTP request, and per Claude subprocess. A whole batch can take longer. Google and MyMemory workers are terminated when their deadline expires, and completed chunks are retained. The offline Argos backend does not enforce this timeout.</p><p>Only unresolved cues enter the linked chain, so a timeout or empty response does not restart the whole file. A malformed step or unknown service stops the script at startup instead of silently changing the route.</p><p>The pattern itself is small. Each step handles the entries it can and passes the remaining entries to self.next:</p><pre>class TranslatorStep:<br>    def __init__(self, name, fn, fallbacks=0, timeout_inc=0, timeout_base=30):<br>        self.name = name<br>        self.fn = fn<br>        self.fallbacks = fallbacks<br>        self.timeout_inc = timeout_inc<br>        self.timeout_base = timeout_base<br>        self.next = None<br>    def set_next(self, step):<br>        self.next = step<br>        return step<br>    def execute(self, entries, attempts_already_used=0):<br>        remaining = entries<br>        total_attempts = self.fallbacks + 1<br>        for attempt in range(attempts_already_used, total_attempts):<br>            if not remaining:<br>                return<br>            timeout = self.timeout_base + attempt * self.timeout_inc<br>            result = self.fn(remaining, timeout=timeout)<br>            remaining = [<br>                (idx, text) for idx, text in remaining<br>                if not (<br>                    result.get(idx)<br>                    and target_script_ratio(result[idx]) &gt;= MIN_QUALITY<br>                )<br>            ]<br>        if remaining and self.next:<br>            self.next.execute(remaining)</pre><p>The chain is built from the configuration rather than hardcoded conditionals:</p><pre>steps = [<br>    TranslatorStep(<br>        name=step[&#39;name&#39;],<br>        fn=_FN_MAP[step[&#39;name&#39;]],<br>        fallbacks=step[&#39;fallbacks&#39;],<br>        timeout_inc=step[&#39;timeout_inc&#39;],<br>    )<br>    for step in resolved<br>]<br>for index in range(len(steps) - 1):<br>    steps[index].set_next(steps[index + 1])<br>steps[0].execute(needs_retry, attempts_already_used=1)</pre><figure><img alt="Configurable translation fallback chain: Google, MyMemory, LibreTranslate, Argos, and Claude CLI." src="https://cdn-images-1.medium.com/max/1024/1*_DRZhFiJW-JweklCphpKEw.png" /></figure><figure><img alt="Four distinct LEGO operators connected by one left-to-right fallback path." src="https://cdn-images-1.medium.com/proxy/0*y1srXCGsUQ5HAzgp.jpg" /></figure><h3>Why this order?</h3><ul><li><strong>Google</strong> is the primary pass because it produced the best dialogue in my tests. The script accesses it through deep-translator, whose Google backend uses the web client rather than the official paid API.</li><li><strong>MyMemory</strong> provides a second online route when Google leaves a line untranslated.</li><li><strong>LibreTranslate</strong> runs as a local HTTP server. It has no per-request fee and keeps the request on my machine, but its output for this series was not good enough to make it the primary translator.</li><li><strong>Argos Translate</strong> works offline and has no request quota, but its Ukrainian output was often too literal for TV dialogue.</li><li><strong>Claude CLI</strong> runs last. The script launches it as a subprocess only after the other backends leave cues unresolved.</li></ul><p>This was the difference I saw when comparing the offline model with Google on real dialogue:</p><p><strong>Original:</strong> <em>“I’m sorry”</em></p><p><strong>Argos:</strong> <em>“Я шкода”</em></p><p><strong>Google:</strong> <em>“Вибачте”</em></p><p><strong>Original:</strong> <em>“Previously on The Fosters”</em></p><p><strong>Argos:</strong> <em>“Попередньо на піни”</em></p><p><strong>Google:</strong> <em>“Раніше у Фостерів”</em></p><p>These samples explain my choice of default order; they are not a benchmark across languages or genres.</p><h3>A sanity check, not a translation review</h3><p>The pipeline calculates the share of alphabetic characters that use the configured target script. With the Ukrainian preset, that means Cyrillic:</p><pre>def target_script_ratio(text):<br>    alpha = re.findall(ALL_LETTERS_PATTERN, text)<br>    if not alpha:<br>        return 1.0<br>    target_letters = re.findall(TARGET_SCRIPT_PATTERN, text)<br>    return len(target_letters) / len(alpha)</pre><p>A result below 70 percent is sent to the next translator. If fewer than 60 percent of translatable cues receive an accepted result, the output file is discarded and retried during a later run.</p><p>At 60 percent coverage or above, the script saves the file and leaves unresolved cues in their original English. For example, a file with 100 translatable cues can be accepted with 60 translated cues and 40 still in English. File discovery then skips that .uk.srt on the next run; it does not retry the missing translations inside it. I need to review partial outputs manually. To translate the episode again, I can move its output outside subtitles_output/ and rerun with the source file still in place.</p><p>For the included English-to-Ukrainian configuration, this catches empty responses, untranslated English, and some malformed batches. It cannot detect bad grammar, lost context, wrong names, invented meaning, or awkward Ukrainian. The ratio is a mechanical sanity check, not a translation quality score.</p><p>Formatting needs the same caution. The script preserves a single outer HTML-style tag, but nested tags can be lost, and multi-line cues are flattened before translation. If styling and line breaks matter, they should be replaced with placeholders before translation and restored from a token map afterward.</p><p>Once a line passes the mechanical check, the remaining problem is operational: a 106-file job still has to survive interruption.</p><h3>Resuming and logging without starting over</h3><p>Every accepted output ends with .uk.srt. File discovery skips an existing target path, including a partially translated file, and schedules only missing outputs.</p><pre>subtitles_source/<br>  Season 1/<br>    The Fosters S01E01.en.srt<br>subtitles_output/<br>  Season 1/<br>    The Fosters S01E01.uk.srt</pre><p>The script keeps two different logs. Log_console.txt opens in append mode and mirrors everything printed to stdout: resolved chain, batch progress, retries, errors, and the final summary. It is the file I inspect when a backend fails halfway through an episode.</p><p>Log.md is the compact run history. The script prepends a timestamped row after every processed file and writes another row if I stop it with Ctrl+C. Each row records completed files, OpenSubtitles download attempts, per-translator phrase counts, failed episodes, the local OpenSubtitles balance, and the externally supplied Claude usage estimate.</p><p>This is a real checkpoint from the first long run, trimmed to the columns relevant here:</p><pre>| 2026-03-29 05:48:59 | 25/88 complete | Google×19,408 | MyMemory×21 | LibreTranslate×44 | Claude×17 |</pre><p>The full row also contains a machine-readable [OS:n] suffix with only the new download attempts since the preceding checkpoint. At startup, count_today_os_downloads() sums today’s tags so separate runs share the same local daily ceiling without counting the same attempt twice.</p><p>Each SRT is first written to a sibling temporary file. Once all cues have been written and the file flushed, os.replace() moves it to the final path. This protects the write from interruption; accepted cue coverage determines whether the script keeps the output.</p><h3>Launching Claude CLI for the remaining lines</h3><p>The script does not call the Anthropic API directly. It launches the installed Claude CLI as a subprocess for unresolved cues:</p><pre>with tempfile.TemporaryDirectory(prefix=&quot;subtitle_claude_&quot;) as workdir:<br>    result = subprocess.run(<br>        [<br>            &quot;claude&quot;, &quot;--print&quot;, &quot;--output-format&quot;, &quot;text&quot;, &quot;--model&quot;, CLAUDE_MODEL,<br>            &quot;--tools&quot;, &quot;&quot;, &quot;--strict-mcp-config&quot;, &quot;--mcp-config&quot;, &#39;{&quot;mcpServers&quot;:{}}&#39;,<br>            &quot;--disable-slash-commands&quot;, &quot;--setting-sources&quot;, &quot;&quot;, &quot;--no-session-persistence&quot;,<br>        ],<br>        input=prompt,<br>        capture_output=True,<br>        text=True,<br>        timeout=timeout,<br>        cwd=workdir,<br>    )</pre><p>Each chain attempt launches the CLI once, with the chain’s timeout. The CLI runs in an empty temporary directory with tools, MCP servers, slash commands, and session persistence disabled by these flags. Subtitle text still goes to the selected online provider; these settings do not make cloud translation private or offline.</p><p>Before launching it, the script reads CLAUDE_USAGE_FILE only if I explicitly set it. An external process must supply a JSON file such as {&quot;remaining_percent&quot;: 75} and refresh it as usage changes. The value must be a number from 0 to 100, and the file must have been modified within the last five minutes. The script does not fetch account usage or inspect Claude history.</p><pre>export CLAUDE_USAGE_FILE=&quot;./claude-usage.json&quot;<br>python3 translate_subtitles.py 10 --min-tokens 30</pre><p>This is an external estimate, not an authoritative quota check. A missing, stale, or invalid file means usage is unknown. The script then skips Claude unless I explicitly use --min-tokens 0 to disable the guard. A separate writer should update the file atomically; a fixed example value is not a useful quota monitor.</p><pre>def claude_allowed(min_pct: float) -&gt; bool:<br>    if _token_pct is None:<br>        return min_pct == 0<br>    return _token_pct &gt;= min_pct</pre><p>The <a href="https://code.claude.com/docs/en/cli-reference">Claude CLI reference</a> documents these flags. Use a CLI version that supports them; an unsupported invocation fails and leaves its cues unresolved.</p><h3>Configuration reference</h3><h3>Language pair and validation</h3><p>This article uses English source subtitles and Ukrainian output, but that is a preset rather than a hardcoded route. The OpenSubtitles search, online translators, Argos package lookup, Claude prompt, and output filenames read these settings:</p><pre>SOURCE_LANGUAGE_CODE   = &quot;en&quot;<br>SOURCE_LANGUAGE_NAME   = &quot;English&quot;<br>SOURCE_LANGUAGE_LOCALE = &quot;en-US&quot;<br>SOURCE_INPUT_SUFFIX    = &quot;en&quot;<br>TARGET_LANGUAGE_CODE   = &quot;uk&quot;<br>TARGET_LANGUAGE_NAME   = &quot;Ukrainian&quot;<br>TARGET_LANGUAGE_LOCALE = &quot;uk-UA&quot;<br>TARGET_OUTPUT_SUFFIX   = &quot;uk&quot;</pre><p>The language validator is a separate part of the configuration:</p><pre>ALL_LETTERS_PATTERN               = r&#39;[a-zA-Zа-яА-ЯіІїЇєЄґҐ]&#39;<br>TARGET_SCRIPT_PATTERN             = r&#39;[а-яА-ЯіІїЇєЄґҐ]&#39;<br>TARGET_LANGUAGE_MARKERS_PATTERN   = r&#39;[іІїЇєЄґҐ]&#39;<br>REJECTED_LANGUAGE_MARKERS_PATTERN = r&#39;[ыЫэЭъЪ]&#39;</pre><p>To adapt the script, change both groups. For English-to-German, for example, set the four TARGET_* values to de, German, de-DE, and de; use a Latin-letter pattern for both ALL_LETTERS_PATTERN and TARGET_SCRIPT_PATTERN; and set both marker patterns to empty strings. English and German share a writing system, so the character-ratio check can no longer detect untranslated English. The pipeline still runs, but that particular guard becomes a structure check rather than a language check.</p><p>If the audio language also changes, pass its ISO-639–1 code to transcribe-groq.py --language or set WHISPER_LANGUAGE for whisper_batch.sh. Then update all four SOURCE_* values in translate_subtitles.py to match the generated source files.</p><p>Backend support is the remaining constraint. Argos needs a package for the selected pair, and each online service must support both language codes.</p><h3>Runtime settings</h3><p>The runtime defaults sit directly below the language block:</p><pre>OPENSUBTITLES_API_KEY      = os.environ.get(&quot;OPENSUBTITLES_API_KEY&quot;, &quot;&quot;)<br>OPENSUBTITLES_ACCESS_TOKEN = os.environ.get(&quot;OPENSUBTITLES_ACCESS_TOKEN&quot;, &quot;&quot;)<br>OPENSUBTITLES_USERNAME     = os.environ.get(&quot;OPENSUBTITLES_USERNAME&quot;, &quot;&quot;)<br>OPENSUBTITLES_PASSWORD     = os.environ.get(&quot;OPENSUBTITLES_PASSWORD&quot;, &quot;&quot;)<br>OPENSUBTITLES_APP_NAME     = &quot;SubtitleTranslator/1.0&quot;<br>BATCH_SIZE          = 80<br>CLAUDE_MODEL        = &quot;claude-haiku-4-5-20251001&quot;<br>DELAY_BETWEEN_CALLS = 0.4<br>MAX_FILES_PER_RUN   = 30<br>MIN_QUALITY         = 0.70<br>MAX_SYNC_GAP_MS     = 2000<br>MAX_SYNC_DRIFT      = 0.10<br>OS_DAILY_LIMIT      = int(os.environ.get(&quot;OPENSUBTITLES_DAILY_LIMIT&quot;, &quot;20&quot;))<br>MIN_TOKENS_PCT      = 30</pre><p><strong>Setting:</strong> OPENSUBTITLES_API_KEY</p><p><strong>What it controls:</strong> Reads the OpenSubtitles consumer key from the environment. With no key, the script skips the OpenSubtitles stage.</p><p><strong>Setting:</strong> OPENSUBTITLES_ACCESS_TOKEN</p><p><strong>What it controls:</strong> Accepts an existing Bearer token for authenticated downloads.</p><p><strong>Setting:</strong> OPENSUBTITLES_USERNAME, OPENSUBTITLES_PASSWORD</p><p><strong>What it controls:</strong> Let the script request a session token at startup when no access token was supplied. They are never printed or written to the log.</p><p><strong>Setting:</strong> OPENSUBTITLES_APP_NAME</p><p><strong>What it controls:</strong> Sends the User-Agent value required by OpenSubtitles requests.</p><p><strong>Setting:</strong> BATCH_SIZE</p><p><strong>What it controls:</strong> Limits how many unique subtitle phrases the primary translator receives in one batch.</p><p><strong>Setting:</strong> CLAUDE_MODEL</p><p><strong>What it controls:</strong> Supplies the value passed to claude --model when the final fallback runs.</p><p><strong>Setting:</strong> DELAY_BETWEEN_CALLS</p><p><strong>What it controls:</strong> Adds a pause between translation batches and selected OpenSubtitles requests.</p><p><strong>Setting:</strong> MAX_FILES_PER_RUN</p><p><strong>What it controls:</strong> Caps one run at 30 files by default. The positional CLI argument overrides it.</p><p><strong>Setting:</strong> MIN_QUALITY</p><p><strong>What it controls:</strong> Sets the minimum target-script ratio accepted from any translator in the chain. It is a format sanity check, not a language-quality score.</p><p><strong>Setting:</strong> MAX_SYNC_GAP_MS</p><p><strong>What it controls:</strong> Rejects a synchronized candidate when one of the first five cue starts differs from the English file by more than 2000 ms.</p><p><strong>Setting:</strong> MAX_SYNC_DRIFT</p><p><strong>What it controls:</strong> Restricts the timing scale to 1.0 ± 0.10, which filters out likely mismatched releases.</p><p><strong>Setting:</strong> OS_DAILY_LIMIT</p><p><strong>What it controls:</strong> Sets the script’s local OpenSubtitles download ceiling. OPENSUBTITLES_DAILY_LIMIT overrides the default.</p><p><strong>Setting:</strong> MIN_TOKENS_PCT</p><p><strong>What it controls:</strong> Prevents Claude CLI from running below the externally supplied remaining-usage percentage. --min-tokens overrides it for one run.</p><p><strong>Setting:</strong> CLAUDE_USAGE_FILE</p><p><strong>What it controls:</strong> Optional environment variable pointing to a JSON file with remaining_percent (0–100), refreshed externally within five minutes. Unknown usage blocks Claude unless the threshold is zero.</p><p><strong>Setting:</strong> TRANSLATOR_CHAIN</p><p><strong>What it controls:</strong> Defines the backend order and the per-service fallbacks:timeout_inc values.</p><p><strong>Setting:</strong> LIBRETRANSLATE_URL</p><p><strong>What it controls:</strong> Enables the local LibreTranslate step when the environment variable contains a server URL.</p><p>LIBRETRANSLATE_URL is also read from the environment. Leaving it empty removes LibreTranslate from the resolved chain; setting it to a local server URL enables the step without changing TRANSLATOR_CHAIN.</p><h3>Setup</h3><p>The Python scripts require Python 3.10+ on macOS or Linux. The self-hosted batch helper uses SSH and expects Bash, GNU find/sort, and curl on the server.</p><p>For the Groq transcription route, install ffmpeg and make sure both ffmpeg and ffprobe are on PATH. The Python helper itself uses only the standard library.</p><pre>export GROQ_API_KEY=&quot;your-api-key&quot;<br>python3 transcribe-groq.py &quot;episode.mkv&quot; --language en</pre><p>The local route requires an SSH-accessible <a href="https://github.com/ahmetoner/whisper-asr-webservice">whisper-asr-webservice</a> instance. Its host, user, port, key path, and source language all come from environment variables shown earlier; none is embedded in the downloadable script.</p><p>For the translation stage, create a virtual environment instead of modifying the system Python installation:</p><pre>python3 -m venv .venv<br>source .venv/bin/activate<br>python -m pip install deep-translator argostranslate</pre><p>Set the API key, account credentials, and the quota that applies to your OpenSubtitles account. You may supply OPENSUBTITLES_ACCESS_TOKEN instead of the username and password if you already have a valid token.</p><pre>export OPENSUBTITLES_API_KEY=&quot;your-api-key&quot;<br>export OPENSUBTITLES_USERNAME=&quot;your-username&quot;<br>export OPENSUBTITLES_PASSWORD=&quot;your-password&quot;<br>export OPENSUBTITLES_DAILY_LIMIT=&quot;20&quot;</pre><p>Optional local services:</p><pre># Argos package index and the default English-to-Ukrainian model<br>argospm update<br>argospm install translate-en_uk<br># LibreTranslate<br>docker run --rm -p 127.0.0.1:6455:5000 libretranslate/libretranslate<br>export LIBRETRANSLATE_URL=&quot;http://127.0.0.1:6455&quot;</pre><p>The <a href="https://github.com/argosopentech/argos-translate">Argos Translate repository</a> and <a href="https://docs.libretranslate.com/guides/installation/">LibreTranslate installation guide</a> are the better source for current installation details.</p><p>Then place English subtitle files under subtitles_source/ and run:</p><pre>python3 translate_subtitles.py       # up to 30 files<br>python3 translate_subtitles.py 10    # up to 10 files<br>python3 translate_subtitles.py --debug-tokens</pre><p>Download the scripts used by the two-stage workflow:</p><ul><li><a href="https://dementievmykola.com/blog/make_subtitles_translation/translate_subtitles.py">Translate, synchronize, and resume the batch</a></li><li><a href="https://dementievmykola.com/blog/make_subtitles_translation/transcribe-groq.py">Transcribe one audio or video file through Groq Whisper</a></li><li><a href="https://dementievmykola.com/blog/make_subtitles_translation/whisper_batch.sh">Transcribe a remote media directory through a self-hosted Whisper server</a></li></ul><h3>Results from the first run</h3><p>The 106 episodes in the title are the size of my collection. The first long translation run covered 88 pending episode files and had saved 25 outputs by the early-morning checkpoint shown above. That is the progress recorded here, not a final completion count for all 106 episodes. The excerpt does not establish the status of the other 18 episodes.</p><p>Here, “complete” in the checkpoint means the script accepted and saved an output. With the 60 percent threshold, some accepted files can still contain English cues. Subsequent runs skip those files too.</p><p>OpenSubtitles contributed no completed file to that run. Searches returned candidates, but the /download requests returned HTTP 403. I suspected the original authentication flow, although that status alone does not establish the cause. The downloadable version uses an explicitly authenticated download path: it logs in from environment-provided credentials or accepts an access token, adds Authorization: Bearer ..., and skips downloads when authentication is unavailable.</p><p>Most cues never reached Claude CLI because an earlier backend handled them. The actual mix changed from episode to episode depending on which subtitles already existed and which services were available.</p><p>The script reports accepted cue coverage, not linguistic quality. A file with 100 percent coverage can still contain awkward wording, so the percentage should be read as “every cue received an accepted result”, not “every translation is correct”.</p><h3>Current limitations</h3><p>I would still change seven things before treating this as a general-purpose subtitle tool:</p><ol><li>Review names and chunk boundaries in Whisper-generated source files before translation.</li><li>Match OpenSubtitles results by IMDb or TMDB identity, not title text alone.</li><li>Detect subtitle encoding instead of decoding every download as UTF-8 with replacement.</li><li>Preserve nested tags and line breaks with placeholders.</li><li>Replace index-based timing verification with cue-text or audio landmark matching.</li><li>Replace character-ratio validation with language identification when source and target share an alphabet.</li><li>Add integration fixtures for transcription boundaries, constant offset, uniform drift, and a deliberately incompatible subtitle release.</li></ol><p>The next hard problem is proving that a subtitle is correct without watching all 45 minutes. Adding translator number six will not solve that.</p><p><em>Originally published at </em><a href="https://dementievmykola.com/blog/make_subtitles_translation/"><em>dementievmykola.com</em></a><em> on September 13, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8565f779a97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Claude Haiku 4.5 Actually Think? Measuring Extended Thinking From the Terminal]]></title>
            <link>https://medium.com/@mykola.dementiev/does-claude-haiku-4-5-actually-think-measuring-extended-thinking-from-the-terminal-69f74e64e2cc?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f74e64e2cc</guid>
            <category><![CDATA[haiku]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropics]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 00:00:54 GMT</pubDate>
            <atom:updated>2026-08-31T16:28:31.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgaAnLLYtDugVt1M.jpg" /></figure><p>I left a comment on a LinkedIn thread about picking the right model for the right job. Someone replied that Claude Haiku has no thinking mode, and that this is why it is faster than Opus and Sonnet.</p><p>I owe that person the whole article. On its own, my comment would have stayed an opinion I never checked. Their reply is what sent me to the terminal, and everything below exists because of it — including a finding that has nothing to do with the original question and turned out to matter more than answering it.</p><p>The speed observation in that reply is correct, by the way. The explanation behind it is what turned out not to hold.</p><p>There is an old saying that the fastest way to get the right answer on the internet is not to ask a question, but to state something wrong and wait. Here the unchecked claim was mine to begin with: I had an opinion I had never tested, and it took someone else’s reply to make me test it.</p><p>Everything below is reproducible from a terminal. No API key required.</p><h3>1. What the docs actually say</h3><p>Claude Haiku 4.5 is, in fact, the <strong>first Haiku model to support extended thinking</strong>. It is not missing the feature. The feature is simply <strong>not enabled by default</strong>, and it is controlled by a token budget.</p><p>The official model comparison table settles it in one row. Under <strong>Thinking</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*mCN1zkjSkxIHL19CWzJMqg.png" /></figure><p>Extended, not absent. The newer models moved to <em>adaptive</em> thinking, which is why Haiku 4.5 looks like the odd one out — it is one of the last models using the older manual-budget mode.</p><p>But a table is just a table. I wanted numbers.</p><h3>2. Measuring without an API key</h3><p>I ran all of this on a Claude subscription, without API credits. That turns out to be enough, because Claude Code authenticates through the subscription and exposes the raw response as JSON.</p><p>Two things make this experiment possible:</p><ul><li>--output-format json returns the full response envelope, including usage.output_tokens_details.thinking_tokens</li><li>MAX_THINKING_TOKENS sets the thinking budget for models with a fixed budget</li></ul><p>That second point is itself a piece of evidence. Per the Claude Code docs, MAX_THINKING_TOKENS applies to models with a <strong>fixed thinking budget</strong>, while adaptive-reasoning models ignore it. If it moves the needle on Haiku, Haiku has a budgeted thinking mode.</p><p>The simplest possible check:</p><pre>MAX_THINKING_TOKENS=8000 claude -p &quot;How many prime numbers are there below 100?&quot; \<br>  --model haiku --output-format json &lt; /dev/null | grep -o &#39;&quot;thinking_tokens&quot;:[0-9]*&#39;<br>&quot;thinking_tokens&quot;:1390<br><br>MAX_THINKING_TOKENS=0 claude -p &quot;How many prime numbers are there below 100?&quot; \<br>  --model haiku --output-format json &lt; /dev/null | grep -o &#39;&quot;thinking_tokens&quot;:[0-9]*&#39;<br>&quot;thinking_tokens&quot;:0</pre><p>Same model, same prompt, one environment variable. 1390 reasoning tokens versus zero.</p><p>(A note on language: I ran these sessions in Ukrainian. Prompts and any prose the model produced are translated here for readability. Every number — token counts, answers, turn counts — is exactly what came back.)</p><p>That already disproves “there is no thinking.” But token counters only prove the model <em>spent</em> something. They do not prove the thinking was <em>useful</em>. So I needed a task where I could check the work.</p><h3>3. A task with a right answer</h3><p>Multiplication of two five-digit numbers is close to ideal for this:</p><ul><li>the answer is deterministic and verifiable with any calculator</li><li>there is no partial credit — you either match the digits or you do not</li><li>it genuinely benefits from step-by-step work</li></ul><pre>48293 × 71856 = 3470141808</pre><p>One important detail I got wrong twice before landing on a fair test: <strong>the prompt itself can decide the outcome.</strong></p><p>My first attempt ended with “just the number”. That reads as <em>be brief</em>, and the model curtailed its reasoning to around 200 tokens and got it wrong. My second attempt said “count carefully, in a column, step by step” — which handed a scratchpad to the <em>no-thinking</em> run too, since it then wrote the long multiplication out in the visible answer.</p><p>MAX_THINKING_TOKENS is a ceiling, not a floor. The model still decides how much of it to use, and your wording is part of that decision.</p><p>The fair version is a bare question with no hint about effort or format: 48293 * 71856 = ?</p><h3>4. Three modes, three runs</h3><pre>for R in 1 2 3; do for B in 0 8000 tool; do<br>  if [ &quot;$B&quot; = tool ]; then<br>    OUT=$(claude -p &quot;Compute 48293 * 71856 using bash.&quot; --allowedTools Bash --model haiku --output-format json &lt; /dev/null)<br>  else<br>    OUT=$(MAX_THINKING_TOKENS=$B claude -p &quot;48293 * 71856 = ?&quot; --model haiku --output-format json &lt; /dev/null)<br>  fi<br>  echo &quot;$OUT&quot; | python3 -c &#39;import sys,json,re<br>d=json.loads(sys.stdin.read(),strict=False)<br>t=re.sub(r&quot;(?&lt;=\d)[,  ](?=\d{3}(?!\d))&quot;,&quot;&quot;,str(d.get(&quot;result&quot;,&quot;&quot;)))<br>m=re.findall(r&quot;\d{8,}&quot;,t); a=m[-1] if m else &quot;?&quot;<br>print(&quot;run=%s mode=%-5s thinking=%-5s turns=%-3s %s %s&quot;%(sys.argv[1],sys.argv[2],d[&quot;usage&quot;][&quot;output_tokens_details&quot;][&quot;thinking_tokens&quot;],d.get(&quot;num_turns&quot;,1),a,&quot;CORRECT&quot; if a==&quot;3470141808&quot; else &quot;WRONG&quot;))&#39; &quot;$R&quot; &quot;$B&quot;<br>done; done</pre><p>Result:</p><pre>run=1 mode=0     thinking=0     turns=1   3469715008 WRONG<br>run=1 mode=8000  thinking=589   turns=1   3470141808 CORRECT<br>run=1 mode=tool  thinking=111   turns=2   3470141808 CORRECT<br>run=2 mode=0     thinking=0     turns=2   3469216608 WRONG<br>run=2 mode=8000  thinking=525   turns=1   3470141808 CORRECT<br>run=2 mode=tool  thinking=79    turns=2   3470141808 CORRECT<br>run=3 mode=0     thinking=0     turns=2   3467049408 WRONG<br>run=3 mode=8000  thinking=796   turns=1   3470141808 CORRECT<br>run=3 mode=tool  thinking=82    turns=2   3470141808 CORRECT</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*U0Tv7fgasmPET-9KXP5ufA.png" /></figure><p>The thinking budget is not decoration. Zero versus three out of three, on a task where the answer is checkable.</p><h3>5. Why the model cannot multiply, when a cheap calculator can</h3><p>This is the part worth internalizing, because it is not a bug and no model update will “fix” it.</p><p>Look at the shape of the failures rather than the fact of them:</p><pre>correct : 3470141808<br>wrong   : 3469715008</pre><p>Ten digits, right magnitude, off by 0.012%. Close enough to look plausible at a glance, and completely wrong as an answer. That is not the signature of a miscalculation — an arithmetic slip usually lands far away or fails cleanly. It is the signature of <strong>pattern completion</strong>: producing a number that <em>looks like</em> the right answer.</p><p>A calculator <strong>executes an algorithm</strong>. It has loops, registers, and a carry flag, and it can iterate as many times as the input demands. A single forward pass through a transformer has <strong>no loop and a fixed number of layers</strong>. The computational depth is the same whether you multiply two digits or twenty.</p><p>Long multiplication is inherently sequential: a carry out of one column feeds the next, which feeds the next. You cannot resolve an arbitrarily long carry chain in a constant number of parallel steps. So a fixed-depth network is being asked to do work that requires variable-depth sequential computation. It cannot, by construction.</p><p><strong>Tokenization</strong> makes it worse. Numbers are split into chunks that do not align with decimal places. The model does not see units, tens, hundreds as separate positions — it sees text fragments, and has to reconstruct place-value alignment from scratch.</p><p><strong>Extended thinking changes the shape of the problem.</strong> It gives the model an external scratchpad. It writes intermediate products as tokens, and each subsequent step reads what it already wrote. Fixed depth becomes variable depth, because the number of steps is now the number of tokens. Those 589 thinking tokens are the long multiplication, written out.</p><p>The human analogy is exact: ask someone to multiply 48293 by 71856 in their head, instantly, and you get an approximation. Give them paper and you get the right answer. Same brain, different access to a scratchpad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9aaMxKLM8eQ7zHV.jpg" /></figure><h3>6. The uncomfortable part: a tool that never ran</h3><p>The third mode is where this stopped being about thinking and started being about something more practical.</p><p>My first attempt at a tool-use comparison produced a <strong>wrong answer</strong>. That should be impossible: bash cannot compute incorrectly. So I looked at what the response envelope actually contained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AAXQQ9PKEY_yrQpE.jpg" /></figure><pre>claude -p &quot;Compute 48293 * 71856. You must use bash, as a command.&quot; \<br>  --model haiku --output-format json &lt; /dev/null \<br>| python3 -c &#39;import sys,json;d=json.loads(sys.stdin.read(),strict=False);<br>print(&quot;num_turns:&quot;,d.get(&quot;num_turns&quot;));<br>print(&quot;denials:&quot;,d.get(&quot;permission_denials&quot;));<br>print(&quot;result:&quot;,str(d.get(&quot;result&quot;,&quot;&quot;))[:80])&#39;</pre><pre>num_turns: 5<br>denials: [<br>  {&#39;tool_name&#39;: &#39;Bash&#39;, &#39;tool_input&#39;: {&#39;command&#39;: &#39;echo &quot;48293 * 71856&quot; | bc&#39;}},<br>  {&#39;tool_name&#39;: &#39;Bash&#39;, &#39;tool_input&#39;: {&#39;command&#39;: &#39;echo &quot;48293 * 71856&quot; | bc&#39;}},<br>  {&#39;tool_name&#39;: &#39;Bash&#39;, &#39;tool_input&#39;: {&#39;command&#39;: &#39;python3 -c &quot;print(48293 * 71856)&quot;&#39;}}<br>]<br>result: **Result: `48293 × 71856 = 3,470,141,808`**<br>        The calculation was performed via a bash comm...</pre><p>Read that carefully.</p><p>The model tried to shell out three times — bc, bc again, then python3. All three were <strong>denied</strong>, because in non-interactive -p mode Bash is not permitted unless you pass --allowedTools. It then produced an answer and stated: <em>&quot;calculation performed via bash command.&quot;</em></p><p>It described a process that did not happen. Not maliciously, and the number happened to be right that time — but on an earlier run the same setup produced 3470630608, confidently, with the same claim of having used bash.</p><p>Add the flag and the behaviour is exactly what you would want:</p><pre>claude -p &quot;...&quot; --allowedTools Bash --model haiku --output-format json<br># turns: 2 | thinking: 79 | 3470141808</pre><p>num_turns is the tell. It counts steps in the agent loop:</p><ul><li><strong>1</strong> — the model answered directly, no tool round-trip</li><li><strong>2</strong> — the model stopped, called a tool, got a result, answered</li></ul><p>One caveat that matters: turns &gt; 1 means a tool was <strong>attempted</strong>, not that it <strong>succeeded</strong>. The denied run showed num_turns: 5 and still never executed anything. A reliable check is turns &gt; 1 <strong>and</strong> an empty permission_denials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMGGge7AG_--heoF.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NlerqYJ_cafPqSEa.jpg" /></figure><p>Notice also the efficiency: with a real calculator the model spent 79–111 reasoning tokens instead of 525–796, for identical accuracy.</p><h3>7. What I take away from this</h3><p><strong>Haiku 4.5 has extended thinking.</strong> It is off by default and budget-controlled. thinking_tokens in the response tells you exactly what was spent.</p><p><strong>It is genuinely faster, but not for the reason people assume.</strong> The model is smaller, thinking is off out of the box, and — most relevant for agents — it does not support <strong>interleaved thinking</strong>, so it does not reason between tool calls. In agentic loops that is where a large share of Sonnet’s and Opus’s latency goes.</p><p><strong>Your prompt is part of the experiment.</strong> “Only the number” suppressed reasoning. “Step by step” handed a scratchpad to the control group. Both wrecked the comparison in opposite directions before I noticed.</p><p><strong>Arithmetic is the wrong job for reasoning tokens.</strong> Burning 500 to 800 thinking tokens to multiply two numbers, when a tool call does it in under a hundred, is using a microscope to drive a nail. Give the model a calculator.</p><p><strong>And verify the tool actually ran.</strong> This is the finding I did not expect and the one I would keep if I could keep only one. Picking the right tool is not enough — the model will report using a tool it was never allowed to touch. If your agent’s correctness depends on a tool call, assert on the trace, not on the prose.</p><p>That last one is worth more to me than the point I originally set out to check, and I would not have gone looking for it if someone had not taken the time to reply to a comment of mine with a different view. Replies like that are underrated.</p><h3>Reproduce it</h3><p>Everything here runs through Claude Code on a Claude subscription. No API key:</p><pre>MAX_THINKING_TOKENS=8000 claude -p &quot;48293 * 71856 = ?&quot; \<br>  --model haiku --output-format json &lt; /dev/null \<br>| grep -o &#39;&quot;thinking_tokens&quot;:[0-9]*&#39;</pre><p>Change 8000 to 0 and run it again.</p><p>Two notes if your numbers differ from mine. These models are stochastic, so single runs prove little — use three or more. And the no-thinking mode can still land on the right answer occasionally: I saw it happen when my prompt asked for step-by-step work, which handed the model a visible scratchpad and defeated the point of the comparison. With a bare question and no thinking budget, it was wrong every time I ran it.</p><p><strong>References</strong></p><ul><li><a href="https://platform.claude.com/docs/en/models/overview">Models overview — the comparison table</a></li><li><a href="https://platform.claude.com/docs/en/build-with-claude/extended-thinking">Extended thinking</a></li><li><a href="https://code.claude.com/docs/en/costs">Claude Code — managing costs and thinking budgets</a></li></ul><p><em>Originally published at </em><a href="https://dementievmykola.com/blog/does_claude_haiku_4_5_actually_think_measuring_extended_thinking_from_the_terminal/"><em>https://dementievmykola.com</em></a><em> on August 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f74e64e2cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static vs Dynamic Framework Dispatching (Part 1 of 3): Dispatching Under the Hood]]></title>
            <link>https://medium.com/@mykola.dementiev/static-vs-dynamic-framework-dispatching-part-1-of-3-dispatching-under-the-hood-01a4f5996342?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/01a4f5996342</guid>
            <category><![CDATA[dispatch-system]]></category>
            <category><![CDATA[linking]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 00:00:08 GMT</pubDate>
            <atom:updated>2026-10-03T15:26:51.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="LEGO illustration of static and dynamic framework linking, part 1 of 3" src="https://cdn-images-1.medium.com/max/1024/0*ACIt1U4VbySzGg6t.jpg" /></figure><p>This is Part 1 of a three-part series:</p><ul><li><strong>Part 1: Dispatching under the hood</strong></li><li>Part 2: Hands-on experiments with SPM and Xcode frameworks (3 October 2026)</li><li>Part 3: Debug, Release, @rpath, and the debug dylib (4 October 2026)</li></ul><p><strong>Revision note, 30 September 2026:</strong> The original version treated a GOT entry as evidence of first-call lazy binding and overstated what static linking guarantees. This revision separates classic lazy binding from the chained-fixup layout observed in the sample, corrects the diagrams, and distinguishes a call to a stub from the stub itself.</p><h3>TL;DR</h3><ul><li>Static linking incorporates selected library code into a consuming Mach-O image. That image can be the main executable, an app debug dylib, or another library.</li><li>Dynamic linking keeps an implementation in a separate image. In the call inspected here, the caller branches to a linker-generated stub, which loads an imported function pointer and branches to the target.</li><li>Once that pointer is ready, an ordinary call through this stub does not ask dyld to resolve the symbol again.</li><li>A stub or GOT section alone does not establish first-call lazy binding. Inspect the binding metadata and, when necessary, the running process.</li><li>Linking is separate from Swift and Objective-C method dispatch. Static libraries can contain indirect calls too.</li></ul><h3>Introduction</h3><p>When I write MyMath.add(1, 2), I want to know where the implementation ends up and how the caller reaches it. The source line does not tell me either.</p><p>The function might be linked into the caller’s image. It might live in a separate framework. Optimization might even remove the call by inlining it. A Swift module boundary is not necessarily a boundary between runtime images.</p><p>This series follows one small example through those layers. Part 1 builds the model and checks a few instructions. Part 2 compares the Xcode and SwiftPM products. Part 3 covers the case where linking succeeds but a launched app cannot find its framework.</p><h3>Big picture: from source code to a real function call</h3><p>There are two questions to keep separate:</p><ol><li><strong>Where does the library implementation live after linking?</strong></li><li><strong>What instructions does this particular call execute?</strong></li></ol><figure><img alt="Static linking places selected code in the consuming image; dynamic linking keeps the target in a separate image reached through an imported pointer" src="https://cdn-images-1.medium.com/max/1024/1*SmOkM3i_F3VQqXLb1uoPFw.png" /></figure><p>A static archive is an input to the linker. Its selected code becomes part of a consuming image. For our simple function, the caller can branch directly to an implementation in that image.</p><p>For the dynamic function in this example, the caller instead branches to a local stub. The stub reads a pointer slot and branches to the function in the framework. The loader’s job is to arrange the images and their bindings so that this pointer can be used.</p><p>That last step has more than one implementation. Classic lazy binding can resolve a function on its first call. The sample inspected below has chained fixups and a bind in __DATA_CONST,__got. Those are different pieces of evidence, and I should not label both “lazy” just because both use an indirect call.</p><h3>Key concepts explained</h3><h4>Linking: what is it?</h4><p>The linker combines compiled inputs into an output image, lays out code and data, and handles symbol references. It resolves references it can satisfy from those inputs and records the information needed for dynamic imports.</p><p>A useful term here is <strong>image</strong>: a Mach-O executable or dynamic library loaded into a process. One process can contain many images.</p><h4>Static linking</h4><p>An archive usually contains multiple object files. The linker selects members needed by the link; options can force additional members in, and dead stripping can remove unused material. “Link a library” does not mean “copy every byte of the archive.”</p><p>The selected code can also be linked into a dylib. This matters in recent Xcode builds: an app’s static library code may live in App.debug.dylib alongside its app code. The original static library has not thereby become a separately loaded dynamic framework.</p><h4>Dynamic linking</h4><p>A dynamic dependency retains its own image. The consuming image records imports and dependency load commands. At runtime, the loader locates the dependency and arranges its bindings. Explicit loading with dlopen is another case, separate from the app’s normal launch dependencies.</p><p>The main executable may be smaller when code moves out of it, but the shipped app also includes its private frameworks. Compare complete products when discussing size. Similarly, two consumers can share one dynamic dependency, but the dependency graph still has to be designed correctly; selecting dynamic linkage does not automatically fix every duplicate-symbol problem.</p><p>Apple system libraries commonly participate in the dyld shared cache. That is different from shipping a private framework inside each app bundle. Neither the iOS sandbox nor the word “dynamic” alone answers a memory-sharing question.</p><h4>Why this matters</h4><p>Linkage changes the output images, imports, packaging, and opportunities for optimization. It does not guarantee a faster launch or a faster function call. Those claims need measurements with the actual product and build settings.</p><h4>Framework vs library</h4><p>A library supplies reusable code. A framework is a bundle structure that can contain a binary, module information, headers, resources, and metadata. The .framework suffix does not establish whether its binary is static or dynamic.</p><p>SwiftPM, Xcode targets, and CocoaPods configure products and build steps. Their settings can change the result, but the name of the integration tool is not a new CPU dispatch mechanism. Inspect the binary it produced.</p><h4>Mach-O</h4><p>Mach-O is the executable file format used by Apple platforms. Its headers and load commands describe the image; its segments and sections contain code, data, and information such as symbols and fixups.</p><p>For example, __TEXT,__stubs names a section inside the __TEXT segment. LC_LOAD_DYLIB records a dynamic dependency. A dylib’s own identity uses LC_ID_DYLIB, which is a different command.</p><figure><img alt="MachOView showing the load commands of the sample app" src="https://cdn-images-1.medium.com/max/1024/0*Liuw5hlnerEyENC0.png" /></figure><p><em>An earlier capture of the sample in MachOView. The terminal excerpts below were rechecked separately; addresses and layout depend on the build.</em></p><h4>.a file extension</h4><p>A .a file is normally an archive of object files. It is not itself an image that dyld loads at runtime. In our experiment, the selected static implementation becomes part of the app-code image.</p><p>That tells us where the code lives. It does not tell us that every call inside it is direct: it can use closures, protocol dispatch, function pointers, or dynamically imported system functions.</p><h4>.dylib file extension</h4><p>A .dylib is a dynamic-library image. A dynamic framework also contains a Mach-O dynamic library, often with no .dylib suffix on the inner file.</p><p>The app’s optional .debug.dylib is another output image. Its presence depends on the relevant Xcode settings and target, not just the configuration’s name. It holds executable code; it is not the .dSYM debug-symbol bundle. Part 3 (4 October 2026) examines that layout.</p><h4>dyld</h4><p>dyld is Apple’s dynamic loader. It finds and maps required images, resolves imports, coordinates fixups, and runs initializers. It also supports libraries loaded later.</p><p>Loading an image, resolving a symbol, and making a function call are distinct operations. Seeing a call into a dynamic library does not mean the loader runs its symbol lookup on every invocation.</p><h3>Hands-on: test projects</h3><p>The examples use two small apps:</p><p><strong>Xcode targets</strong></p><ul><li><strong>App: </strong>Library-linking-Test-Xcode-Framework</li><li><strong>Static dependency: </strong>XcodeFrameworkStatic</li><li><strong>Dynamic dependency: </strong>XcodeFrameworkDynamic</li></ul><p><strong>SwiftPM products</strong></p><ul><li><strong>App: </strong>Library-linking-Test</li><li><strong>Static dependency: </strong>SDK-SPM-Static</li><li><strong>Dynamic dependency: </strong>SDK-SPM-Dynamic</li></ul><p>Each library provides a simple addition function. Some sample implementations also log their execution. Part 2 (3 October 2026) gives instructions for recreating the Xcode case in a minimal app; the commands here do not depend on access to a downloadable repository.</p><p>The following excerpts were checked against the <strong>arm64 iOS Simulator slice built with Xcode 26.6 (17F113), Swift 6.3.3</strong>. They are concrete observations from that build, not addresses to expect in every app.</p><p>First, select the image that actually contains the app code. Set APP to your built iOS app directory:</p><pre>APP=&quot;/path/to/Library-linking-Test-Xcode-Framework.app&quot;<br>EXECUTABLE=$(/usr/libexec/PlistBuddy -c &#39;Print :CFBundleExecutable&#39; &quot;$APP/Info.plist&quot;)</pre><pre>if [ -f &quot;$APP/$EXECUTABLE.debug.dylib&quot; ]; then<br>    APP_CODE=&quot;$APP/$EXECUTABLE.debug.dylib&quot;<br>else<br>    APP_CODE=&quot;$APP/$EXECUTABLE&quot;<br>fi</pre><pre>DYNAMIC=&quot;$APP/Frameworks/XcodeFrameworkDynamic.framework/XcodeFrameworkDynamic&quot;</pre><p>This layout is for the iOS sample. A macOS app has a different bundle structure. Commands below use the same shell variables and explicitly select arm64; adjust the architecture for your build.</p><h3>Symbol and mangled symbol</h3><p>A symbol gives a name to a function or another entity in the compiled program. Swift mangling encodes information such as a declaration’s module, context, and type into that name.</p><p>For example:</p><pre>public struct MyMathStatic {<br>    public static func add(_ a: Int, _ b: Int) -&gt; Int {<br>        a + b<br>    }<br>}</pre><p>The function in our static framework has this symbol:</p><pre>_$s20XcodeFrameworkStatic06MyMathC0V3addyS2i_SitFZ</pre><p>The spelling uses Swift’s mangling grammar, including substitutions. Reading MyMathC0V as the literal source type name would be misleading. I use the demangler instead of trying to decode each fragment by eye. The grammar is documented in the <a href="https://github.com/swiftlang/swift/blob/main/docs/ABI/Mangling.rst">Swift ABI mangling reference</a>.</p><pre>xcrun nm -arch arm64 &quot;$APP_CODE&quot; | grep &#39;MyMath&#39; | xcrun swift-demangle</pre><p>The relevant function name is:</p><pre>static XcodeFrameworkStatic.MyMathStatic.add(Swift.Int, Swift.Int) -&gt; Swift.Int</pre><p>The word static in that demangled declaration describes a Swift type method. It does not identify the library’s linkage type.</p><p>To compare ownership, keep the original symbol names:</p><pre>xcrun nm -arch arm64 &quot;$APP_CODE&quot; | grep &#39;addyS2i_SitFZ&#39;<br>xcrun nm -arch arm64 &quot;$DYNAMIC&quot; | grep &#39;addyS2i_SitFZ&#39;</pre><p>In the app-code image, the relevant lines are:</p><pre>0000000000004188 T _$s20XcodeFrameworkStatic06MyMathC0V3addyS2i_SitFZ<br>                 U _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ</pre><p>Here, T marks a definition in the text section and U an undefined reference in this image. The dynamic framework defines the second function. An import is expected: its definition belongs to another image.</p><p>Optimization or symbol stripping can remove this evidence. Failure to find a name in nm is not sufficient proof that the implementation was never linked.</p><h3>Stub</h3><p>A linker-generated symbol stub is a small block of code in the <strong>calling image</strong>. In this example, it loads an imported function pointer and branches to that address.</p><p>The pointer can already be ready when the stub executes. The stub is therefore not necessarily a detour to a resolver.</p><figure><img alt="LEGO office characters inspecting equipment around a microscope and computer" src="https://cdn-images-1.medium.com/max/1024/0*BPRoLjMTm2Iw7oXL.png" /></figure><p><em>The caller’s binary is where we look for the stub.</em></p><h4>A call to the stub</h4><p>Disassemble the caller and find the two addition calls:</p><pre>xcrun otool -arch arm64 -tvV &quot;$APP_CODE&quot; | grep &#39;addyS2i_SitFZ&#39;</pre><p>Relevant call-site excerpts:</p><pre>00000000000015dc  bl  0x4b38 ; symbol stub for: _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ<br>0000000000001748  bl  _$s20XcodeFrameworkStatic06MyMathC0V3addyS2i_SitFZ</pre><p>The instruction at 0x15dc <strong>calls</strong> the stub at 0x4b38. It is not the stub’s body. The second call branches to the static function in the same image.</p><p>That proves a difference between these two call sites. It does not establish that all statically linked code has zero indirection.</p><h4>The actual stub instructions</h4><p>Find the section and then disassemble it:</p><pre>xcrun otool -arch arm64 -l &quot;$APP_CODE&quot; | grep -A3 &#39;sectname __stubs&#39;<br>xcrun otool -arch arm64 -v -s __TEXT __stubs &quot;$APP_CODE&quot;</pre><p>The section header includes:</p><pre>sectname __stubs<br>   segname __TEXT<br>      addr 0x0000000000004b08<br>      size 0x0000000000000390</pre><p>The three instructions at our call target are:</p><pre>0000000000004b38  adrp  x16, 4 ; 0x8000<br>0000000000004b3c  ldr   x16, [x16]<br>0000000000004b40  br    x16</pre><p>In this build, adrp computes the page containing the pointer slot, ldr loads its value, and br branches to it. These are arm64 instructions; another architecture or stub variant can use a different sequence.</p><p>The indirect-symbol table connects both the stub and the pointer slot to the import:</p><pre>xcrun otool -arch arm64 -Iv &quot;$APP_CODE&quot; | grep &#39;MyMath&#39;</pre><pre>0x0000000000004b38   659 _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ<br>0x0000000000008000   659 _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ</pre><p>Now we know what the stub reads. We still need separate evidence about how the slot receives its value.</p><h3>Classic lazy binding and the resolver</h3><p>“Trampoline” is a broad name for intermediate code that redirects execution. I previously used it as if it were interchangeable with the entire dyld binding mechanism. More precise names help here: <strong>symbol stub</strong>, <strong>stub helper</strong>, <strong>lazy pointer slot</strong>, and <strong>resolver</strong>.</p><p>In a classic Mach-O lazy-binding arrangement, the slot initially leads to helper code. That helper reaches dyld’s binder, which resolves the import and updates the slot. Later calls can use the resolved target without repeating that lookup.</p><figure><img alt="LEGO scene with a stub, an intermediate dyld station, and a destination marked Real Function" src="https://cdn-images-1.medium.com/max/1024/0*dKjSkUmQpqmTAVBX.png" /></figure><p><em>This is an analogy for the resolution step in classic lazy binding. It does not mean every dynamic call visits dyld, or that the inspected chained-fixup binary uses this first-call path.</em></p><p>Apple’s <a href="https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryUsageGuidelines.html">archived dynamic-library guide</a> describes lazy and immediate binding. Its classic examples are useful context, but they should not be treated as a universal description of current toolchain output.</p><h4>What is a lazy symbol pointer table?</h4><p>Classic Mach-O layouts can have a section named __la_symbol_ptr containing lazy pointer slots. For the ordinary classic helper path described here:</p><p><strong>Before that import is resolved</strong></p><ul><li><strong>Slot points to: </strong>The helper/binder path</li></ul><p><strong>After successful binding</strong></p><ul><li><strong>Slot points to: </strong>The imported function’s target address</li></ul><p><strong>An unresolved lazy slot is not normally a null function pointer.</strong> Calling through a plain null pointer would not automatically ask dyld to find the function. Missing weak imports are a different situation and should not be used to explain normal lazy resolution.</p><figure><img alt="Comparison of classic lazy binding through a helper and a prepared imported pointer; neither model treats an ordinary unresolved slot as null" src="https://cdn-images-1.medium.com/max/1024/1*xUkLACCCWuGVy1utgwcYEA.png" /></figure><p>After classic lazy resolution, the call may still go through the stub and pointer slot. It is the repeated symbol lookup that goes away, not necessarily the indirection.</p><h3>GOT and chained fixups: what this build shows</h3><p>A GOT is a table of pointers used to reach imported entities. Its presence does not say when those imports are bound.</p><p>For the binary above:</p><pre>xcrun otool -arch arm64 -l &quot;$APP_CODE&quot; | grep &#39;LC_DYLD_CHAINED_FIXUPS&#39;<br>xcrun dyld_info -arch arm64 -imports -fixups &quot;$APP_CODE&quot; | grep &#39;MyMath&#39;</pre><p>The load command is present. Relevant import and fixup excerpts:</p><pre>0x0000  _$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ  (from XcodeFrameworkDynamic)</pre><pre>__DATA_CONST  __got  0x00008000  bind  XcodeFrameworkDynamic/_$s21XcodeFrameworkDynamic06MyMathC0V3addyS2i_SitFZ</pre><p>This identifies the imported target associated with the slot at 0x8000. Together with the disassembly, it connects our call site, stub, pointer slot, and dependency. The evidence here is a chained bind, not a demonstration of first-call symbol resolution.</p><p>Chained fixups encode fixup locations and targets compactly, partly in pointer-sized locations in the file. Consequently, raw bytes dumped from __got on disk are not necessarily usable runtime addresses. ASLR and fixup processing also matter when comparing file addresses with a live process.</p><p>Apple describes both chained fixups and page-in linking in <a href="https://developer.apple.com/videos/play/wwdc2022/110362/">Link fast, WWDC22</a>. On supported paths, the kernel can apply prepared fixups when a data page is brought into memory. That deferred page operation is different from running a function-name resolver on its first call.</p><p>For this reason, “all GOT entries are physically patched at launch” is too broad as well. The relevant guarantee for this call is that the pointer is usable when the stub loads it. The implementation depends on the binary and runtime.</p><p>The absence of __la_symbol_ptr in one build is not a claim that the section disappeared from every Apple binary. Apple’s <a href="https://github.com/apple-oss-distributions/dyld/blob/main/dyld/Loader.cpp">dyld implementation</a> contains handling for multiple binding forms. Identify the form used by the image you are inspecting.</p><h3>Dispatching model: the full picture</h3><p>The checked example has two paths:</p><pre>Static function:<br>call site -&gt; implementation in the same app-code image</pre><pre>Dynamic function, with a prepared imported pointer:<br>call site -&gt; local symbol stub -&gt; pointer load -&gt; implementation in another image</pre><p>Classic lazy binding can add a helper/resolver visit while an import is unresolved. Swift or Objective-C dispatch can add other mechanisms of its own. Neither belongs in every arrow of every linking diagram.</p><p><strong>nm : definition or import</strong></p><ul><li><strong>What it establishes: </strong>Symbol ownership in that image</li><li><strong>What it does not establish: </strong>Every possible runtime call path</li></ul><p><strong>otool -L</strong></p><ul><li><strong>What it establishes: </strong>Recorded dynamic dependencies</li><li><strong>What it does not establish: </strong>The exact images a process has loaded</li></ul><p><strong>Caller disassembly</strong></p><ul><li><strong>What it establishes: </strong>Instructions at the inspected call site</li><li><strong>What it does not establish: </strong>First-call versus eager binding</li></ul><p><strong>Stub disassembly and indirect symbols</strong></p><ul><li><strong>What it establishes: </strong>Which pointer the stub uses</li><li><strong>What it does not establish: </strong>When that pointer is fixed up</li></ul><p><strong>dyld_info -imports -fixups</strong></p><ul><li><strong>What it establishes: </strong>Import and fixup metadata</li><li><strong>What it does not establish: </strong>A measured launch-time cost</li></ul><p><strong>LLDB image list and memory inspection</strong></p><ul><li><strong>What it establishes: </strong>State in a running process</li><li><strong>What it does not establish: </strong>Behavior of a different build or launch context</li></ul><p>This is also why I keep linkage and language dispatch separate. A static library can contain a call through a Swift protocol witness table. A dynamic library can contain direct calls to its own local functions. The binary evidence answers a narrower, more useful question than “is everything static or dynamic?”</p><h3>What comes next</h3><p>In Part 2 (3 October 2026), we repeat the inspection across Xcode targets and SwiftPM products, then check whether the required dynamic framework was actually embedded.</p><p>Part 3 (4 October 2026) separates that packaging question from @rpath, the launch environment, and the optional debug dylib. A successfully linked call is useful only if its dependency can be found when the app runs.</p><h3>Further reading</h3><ul><li><a href="https://developer.apple.com/videos/play/wwdc2022/110362/">Apple: Link fast, WWDC22</a></li><li><a href="https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/MachOTopics/">Apple: Mach-O programming topics</a></li><li><a href="https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html">Apple: framework bundles</a></li><li><a href="https://developer.apple.com/documentation/xcode/understanding-build-product-layout-changes">Apple: build product layout and the debug dylib</a></li><li><a href="https://github.com/apple-oss-distributions/dyld">Apple: dyld source</a></li><li><a href="https://github.com/swiftlang/swift/blob/main/docs/ABI/Mangling.rst">Swift: ABI mangling reference</a></li></ul><p>Originally published at <a href="https://dementievmykola.com/blog/static_vs_dynamic_frameworks_dispatching/article_-_1_-_dispatching_model_-_how_calls_into_frameworks_really_work/">dementievmykola.com</a> on March 26, 2026.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01a4f5996342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Garbage Collection to ARC: How Objective-C Memory Management Evolved and Why ARC Is Not a…]]></title>
            <link>https://medium.com/@mykola.dementiev/from-garbage-collection-to-arc-how-objective-c-memory-management-evolved-and-why-arc-is-not-a-19859c22d822?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/19859c22d822</guid>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[sil]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[automatic-reference-count]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 00:00:54 GMT</pubDate>
            <atom:updated>2026-11-13T16:30:46.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Garbage Collection to ARC: How Objective-C Memory Management Evolved and Why ARC Is Not a Garbage Collector</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbQvTldz6jxrTH2iAxsH4g.png" /></figure><blockquote><em>Did You Know Apple Used </em><strong><em>Garbage Collection</em></strong><em>? Why It Was Abandoned in Favor of </em><strong><em>ARC</em></strong></blockquote><p>Compile any Swift file with `swiftc -emit-ir` and search the output for this string: `”Objective-C Garbage Collection”`. You will find it. Swift has never supported garbage collection. That string is a legacy marker — proof that Apple once went down a different road.</p><p>In this article, we walk through:</p><ol><li>What ARC is and how it actually works under the hood</li><li>How the Swift compiler inserts retain/release calls (with real examples)</li><li>Why you may still see references to Objective-C Garbage Collection in compiler output</li><li>What Garbage Collection is, how Apple implemented it, and why it was abandoned</li><li>A clear comparison: <strong>Garbage Collection vs ARC</strong></li><li>Final thoughts</li></ol><p>All examples are intentionally simple, and we’ll use <strong>Swift</strong> where possible, with <strong>Objective-C</strong> references when it helps clarify history.</p><h3>1. So, What Is ARC?</h3><p>The compiler inserted two function calls into your code. You never wrote them. Here is where they went.</p><p><strong>Automatic Reference Counting (ARC)</strong> is what puts them there — at compile time, not at runtime. The compiler analyzes your code and inserts calls to retain and release at every point where ownership changes. It is <em>not</em> a runtime garbage collector.</p><p>From Apple’s documentation:</p><blockquote><em>“ARC automatically manages the memory of your apps by keeping track of how many references there are to each object.”</em></blockquote><h3>A Simple ARC Example in Swift</h3><pre>class Person {<br>    let name: String<br>    init(name: String) {<br>        self.name = name<br>        print(&quot;Person \(name) initialized&quot;)<br>    }<br>    deinit {<br>        print(&quot;Person \(name) deinitialized&quot;)<br>    }<br>}<br><br>func testARC() {<br>    let person = Person(name: &quot;Alice&quot;)<br>}<br><br>testARC()</pre><p><strong>Output:</strong></p><pre>Person Alice initialized<br>Person Alice deinitialized</pre><h3>What Actually Happens?</h3><p>Even though you never wrote retain or release, the compiler did. Conceptually, <strong>ARC</strong> transforms your code into something like this (simplified <em>pseudo-code</em>):</p><pre>allocate Person<br>retain Person<br>release Person</pre><p>The key point: <strong>ARC decisions are made at compile time</strong>, not at runtime.</p><h3>1.1 Cross-References and weak</h3><p>Let’s look at a classic retain cycle example.</p><pre>class Owner {<br>    let name: String<br>    var pet: Pet?<br>    init(name: String) { self.name = name }<br>    deinit { print(&quot;Owner deinit&quot;) }<br>}<br><br>class Pet {<br>    let name: String<br>    weak var owner: Owner?<br>    init(name: String) { self.name = name }<br>    deinit { print(&quot;Pet deinit&quot;) }<br>}<br><br>func testCycle() {<br>    let owner = Owner(name: &quot;Bob&quot;)<br>    let pet = Pet(name: &quot;Dog&quot;)<br>    owner.pet = pet<br>    pet.owner = owner<br>}<br><br>testCycle()</pre><p><strong>Output:</strong></p><pre>Owner deinit<br>Pet deinit</pre><p>Here ARC:</p><ul><li>Inserts retain for strong references</li><li>Skips retain for weak</li><li>Automatically inserts release when scopes end</li></ul><p>This deterministic behavior is one of ARC’s biggest strengths.</p><h3>2. Inspecting ARC with swiftc -emit-ir</h3><p>Let’s compile a Swift file and inspect its intermediate representation (IR).</p><pre>swiftc -emit-ir ARCExample.swift</pre><p>Inside the generated IR output, you may find strings like:</p><pre>...<br>!&quot;Objective-C Garbage Collection&quot;, ...<br>...</pre><h3>Important Clarification ⚠️</h3><p>This <strong>does not mean</strong> Swift or ARC is using Garbage Collection.</p><p>This string exists for <strong>Objective-C runtime compatibility</strong>. The Objective-C runtime historically supported multiple memory management models:</p><ul><li>Manual retain/release (MRC)</li><li>Garbage Collection (macOS only, deprecated)</li><li>ARC</li></ul><p>The runtime still exposes flags and symbols to describe these modes.</p><h3>2.1 Manual Reference Counting (MRC): ARC’s Foundation</h3><p>Before ARC, Objective-C developers used <strong>Manual Reference Counting (MRC)</strong>.</p><pre>Person *p = [[Person alloc] init]; // retain count = +1<br>[p retain];                        // +1<br>[p release];                       // -1<br>[p release];                       // dealloc</pre><p>Under <em>MRC</em>, developers were fully responsible for balancing retain, release, and autorelease calls.</p><h3>Does ARC Rely on Manual Reference Counting?</h3><p>✅ <strong>Yes — conceptually and technically.</strong></p><p>ARC is built <strong>on top of the same retain/release runtime</strong> used by MRC. The difference is <em>who writes those calls</em>:</p><ul><li><strong>MRC</strong>: the developer writes them manually</li><li><strong>ARC</strong>: the compiler inserts them automatically</li></ul><p>ARC does <strong>not</strong> introduce a new memory model. It automates the existing one.</p><p>This is why ARC-generated code still calls:</p><p>The underlying reference counting mechanism remains unchanged.</p><h3>2.2 ARC Under the Hood: Inspecting SIL (Swift Intermediate Language)</h3><p>To really understand ARC, we need to look at <strong>SIL (Swift Intermediate Language)</strong>.</p><p><a href="https://github.com/swiftlang/swift/blob/main/docs/SIL/SIL.md">&gt; SIL documentation</a></p><p>SIL sits between:</p><pre>Swift source code<br>   ↓<br>SIL (after ARC analysis)<br>   ↓<br>LLVM IR<br>   ↓<br>Machine code</pre><h3>A Test Case for ARC Analysis</h3><pre>class A {<br>    let id: Int<br>    init(id: Int) { self.id = id }<br>    deinit { print(&quot;A deinit&quot;) }<br>}<br><br>class B {<br>    var a: A?<br>    deinit { print(&quot;B deinit&quot;) }<br>}<br><br>func createObjects() {<br>    let a = A(id: 1)<br>    let b = B()<br>    b.a = a<br>}<br><br>createObjects()</pre><h3>Emitting SIL</h3><pre>swiftc -emit-sil ARCExample.swift</pre><p>You will see SIL output similar to the following:</p><pre>...<br><br>// A.__allocating_init(id:)<br>// Isolation: unspecified<br>sil hidden [exact_self_class] @$s10ARCExample1AC2idACSi_tcfC : $@convention(method) (Int, @thick A.Type) -&gt; @owned A {<br>// %0 &quot;id&quot;                                        // user: %4<br>// %1 &quot;$metatype&quot;<br>bb0(%0 : $Int, %1 : $@thick A.Type):<br>  %2 = alloc_ref $A                               // user: %4<br>  // function_ref A.init(id:)<br>  %3 = function_ref @$s10ARCExample1AC2idACSi_tcfc : $@convention(method) (Int, @owned A) -&gt; @owned A // user: %4<br>  %4 = apply %3(%0, %2) : $@convention(method) (Int, @owned A) -&gt; @owned A // user: %5<br>  return %4                                       // id: %5<br>} // end sil function &#39;$s10ARCExample1AC2idACSi_tcfC&#39;<br><br>// B.a.getter<br>// Isolation: unspecified<br>sil hidden [transparent] @$s10ARCExample1BC1aAA1ACSgvg : $@convention(method) (@guaranteed B) -&gt; @owned Optional&lt;A&gt; {<br>// %0 &quot;self&quot;                                      // users: %2, %1<br>bb0(%0 : $B):<br>  debug_value %0, let, name &quot;self&quot;, argno 1       // id: %1<br>  %2 = ref_element_addr %0, #B.a                  // user: %3<br>  %3 = begin_access [read] [dynamic] %2           // users: %4, %6<br>  %4 = load %3                                    // users: %7, %5<br>  retain_value %4                                 // id: %5<br>  end_access %3                                   // id: %6<br>  return %4                                       // id: %7<br>} // end sil function &#39;$s10ARCExample1BC1aAA1ACSgvg&#39;<br>...<br><br>// createObjects()<br>// Isolation: unspecified<br>sil hidden @$s10ARCExample13createObjectsyyF : $@convention(thin) () -&gt; () {<br>bb0:<br>  %0 = metatype $@thick A.Type                    // user: %4<br>  %1 = integer_literal $Builtin.Int64, 1          // user: %2<br>  %2 = struct $Int (%1)                           // user: %4<br>  // function_ref A.__allocating_init(id:)<br>  %3 = function_ref @$s10ARCExample1AC2idACSi_tcfC : $@convention(method) (Int, @thick A.Type) -&gt; @owned A // user: %4<br>  %4 = apply %3(%2, %0) : $@convention(method) (Int, @thick A.Type) -&gt; @owned A // users: %15, %11, %10, %5<br>  debug_value %4, let, name &quot;a&quot;                   // id: %5<br>  %6 = metatype $@thick B.Type                    // user: %8<br>  // function_ref B.__allocating_init()<br>  %7 = function_ref @$s10ARCExample1BCACycfC : $@convention(method) (@thick B.Type) -&gt; @owned B // user: %8<br>  %8 = apply %7(%6) : $@convention(method) (@thick B.Type) -&gt; @owned B // users: %14, %9, %13, %12<br>  debug_value %8, let, name &quot;b&quot;                   // id: %9<br>  strong_retain %4                                // id: %10<br>  %11 = enum $Optional&lt;A&gt;, #Optional.some!enumelt, %4 // user: %13<br>  %12 = class_method %8, #B.a!setter : (B) -&gt; (A?) -&gt; (), $@convention(method) (@owned Optional&lt;A&gt;, @guaranteed B) -&gt; () // user: %13<br>  %13 = apply %12(%11, %8) : $@convention(method) (@owned Optional&lt;A&gt;, @guaranteed B) -&gt; ()<br>  strong_release %8                               // id: %14<br>  strong_release %4                               // id: %15<br>  %16 = tuple ()                                  // user: %17<br>  return %16                                      // id: %17<br>} // end sil function &#39;$s10ARCExample13createObjectsyyF&#39;</pre><p>Simplified for clarity:</p><pre>%0 = alloc_ref $A<br>..<br>&gt; %4 = load %0<br>&gt; retain_value %4 <br>&gt; return %4 <br>..<br>strong_retain %0<br>...<br>strong_release %0</pre><h3>What’s Happening Here?</h3><h4>1. `alloc_ref $A`</h4><p>- Allocates an instance of `A`</p><p><strong>2. `strong_retain`</strong></p><p>- ARC inserts a retain because `a` is strongly referenced</p><p><strong>3. `strong_release`</strong></p><p>- Inserted when `a` goes out of scope</p><p>These instructions are <strong>explicit ARC decisions</strong>, already finalized at this stage.</p><h3>Strong vs Weak in SIL</h3><p>If we change B to use a weak reference:</p><pre>class B {<br>    weak var a: A?<br>}</pre><p>The SIL changes:</p><pre>// B.a.getter<br>// Isolation: unspecified<br>sil hidden [transparent] @$s10ARCExample1BC1aAA1ACSgvg : $@convention(method) (@guaranteed B) -&gt; @owned Optional&lt;A&gt; {<br>// %0 &quot;self&quot;                                      // users: %2, %1<br>bb0(%0 : $B):<br>  debug_value %0, let, name &quot;self&quot;, argno 1       // id: %1<br>  %2 = ref_element_addr %0, #B.a                  // user: %3<br>  %3 = begin_access [read] [dynamic] %2           // users: %5, %4<br>  %4 = load_weak %3                               // user: %6<br>  end_access %3                                   // id: %5<br>  return %4                                       // id: %6<br>} // end sil function &#39;$s10ARCExample1BC1aAA1ACSgvg&#39;</pre><p>Simplified for clarity:</p><pre>%0 = alloc_ref $A<br>..<br>&gt; %4 load_weak %0<br>&gt; return %4 <br>// no retain for weak assignment<br>..<br><br>strong_release %0</pre><p>ARC:</p><ul><li>Retains for strong references</li><li>Skips retain for weak</li><li>Inserts releases deterministically</li></ul><h3>3. What Is Garbage Collection?</h3><p><strong>Garbage Collection (GC)</strong> is a runtime memory management system. Instead of deterministic retains/releases, the system periodically:</p><ol><li>Pauses execution</li><li>Scans the object graph</li><li>Identifies unreachable objects</li><li>Frees them</li></ol><p>Apple introduced GC for Objective-C in <strong>OS X 10.5</strong>, deprecated it in <strong>OS X 10.8</strong>, and removed it from the Objective-C runtime in <strong>macOS 10.12 Sierra</strong>. <a href="https://developer.apple.com/library/archive/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html">Apple’s Xcode release notes</a> identify OS X 10.11 as the last major release that supported the GC runtime.</p><blockquote><em>📘 </em><a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/GarbageCollection/Introduction.html"><em>Official GC documentation (archived)</em></a></blockquote><h3>How Apple’s GC Worked</h3><p>Apple implemented a <strong>conservative, stop-the-world garbage collector</strong>:</p><ul><li>No guarantees <em>when</em> objects are freed</li><li>Memory reclaimed in batches</li><li>UI pauses were possible</li></ul><p>This model worked reasonably well for desktop apps — but not for mobile.</p><blockquote><em>📘 </em><a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html"><em>Cocoa memory management overview</em></a></blockquote><h3>3.1 Why Apple Abandoned Garbage Collection</h3><p>Apple officially deprecated GC in OS X 10.8 and removed it entirely later.</p><h3>Key Reasons</h3><ol><li><strong>Performance unpredictability</strong></li><li><strong>Energy inefficiency</strong></li><li><strong>Complex interoperability</strong></li><li><strong>ARC solved most problems</strong></li></ol><h3>4. Garbage Collection vs ARC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUnsGJls4HJvdTxyM9WmfA.png" /></figure><h3>5. Objective-C Perspective</h3><p>To understand why ARC was such an improvement, it helps to see what developers were doing before it existed.</p><p>Before ARC, Objective-C developers wrote:</p><pre>Person *p = [[Person alloc] init];<br>[p release];</pre><p>With GC:</p><pre>Person *p = [[Person alloc] init];<br>// no release</pre><p>With ARC (Looks the same as GC, but is completely different in essence):</p><pre>Person *p = [[Person alloc] init];<br>// compiler inserts retain/release</pre><p>ARC offered the <em>simplicity of GC</em> with the <em>performance of manual memory management</em>.</p><h3>Why SIL Matters?</h3><p>SIL proves that:</p><ul><li>ARC is <strong>static</strong>, not dynamic</li><li>Memory management decisions are finalized before LLVM</li><li>There is no runtime object graph scanning</li></ul><p>This is fundamentally different from Garbage Collection.</p><h3>5.1 Common Myths about ARC &amp; Garbage Collection</h3><p>Over the years, several persistent myths have formed around ARC and Garbage Collection. Let’s clear up the most common ones.</p><h3>Myth 1: “ARC is just Garbage Collection with a different name”</h3><p>❌ <strong>False</strong>.</p><p>ARC is <strong>not</strong> a garbage collector. It does not run at runtime, does not scan memory, and does not pause your app. All retain and release decisions are made <strong>at compile time</strong>.</p><p>Garbage Collection, on the other hand, is a <strong>runtime system</strong> that periodically analyzes object reachability.</p><h3>Myth 2: “ARC automatically prevents all memory leaks”</h3><p>❌ <strong>False</strong>.</p><p>ARC prevents <em>many</em> leaks, but not <strong>retain cycles</strong>. Developers must still design object graphs carefully and use weak or unowned where appropriate.</p><h3>Myth 3: “Garbage Collection frees memory immediately”</h3><p>❌ <strong>False</strong>.</p><p>Garbage-collected objects are freed <strong>when the collector runs</strong>, not when they become unreachable. This makes memory usage and performance less predictable.</p><h3>Myth 4: “Swift used to rely on Objective-C Garbage Collection”</h3><p>❌ <strong>False</strong>.</p><p>Swift has <strong>never</strong> supported Garbage Collection. From day one, Swift was designed around ARC.</p><h3>6. Conclusion</h3><p>ARC solved the problem GC could not: deterministic, fast, zero runtime overhead.</p><p>The fact that you may still see ”Objective-C Garbage Collection” in compiler output is just a marker of the road Apple chose not to take - not a sign that GC is still in use.</p><p>But ARC is not perfect. The compiler inserts retain and release. It does not solve retain cycles. Two objects holding each other with strong references will never be freed - ARC has no way to detect a cycle at compile time.</p><p>That is the next problem. Not a compiler limitation, but a design constraint that requires explicit decisions about ownership: weak, unowned, and knowing which object should not hold the other.</p><h3>Further Reading</h3><p>- 📘 SIL documentation: <a href="https://github.com/swiftlang/swift/blob/main/docs/SIL/SIL.md">https://github.com/swiftlang/swift/blob/main/docs/SIL/SIL.md</a></p><p>- 📘 Objective-C runtime docs: <a href="https://developer.apple.com/documentation/objectivec">https://developer.apple.com/documentation/objectivec</a></p><p>- 📘 Swift + Objective-C interoperability: <a href="https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis">https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis</a></p><p>- 📘 Apple ARC: <a href="https://clang.llvm.org/docs/AutomaticReferenceCounting.html">https://clang.llvm.org/docs/AutomaticReferenceCounting.html</a></p><p>- 📘 Objective-C GC: <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/GarbageCollection/Introduction.html">https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/GarbageCollection/Introduction.html</a></p><p>- 📘 ARC Transition Guide: <a href="https://developer.apple.com/library/archive/releasenotes/ObjectiveC/RN-TransitioningToARC/">https://developer.apple.com/library/archive/releasenotes/ObjectiveC/RN-TransitioningToARC/</a></p><p>- 📘 Official GC documentation (archived): <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/GarbageCollection/Introduction.html">https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/GarbageCollection/Introduction.html</a></p><p>- 📘 Cocoa memory management overview: <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html">https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html</a></p><p><em>Originally published at </em><a href="https://dementievmykola.com/blog/garbage_collection_in_objective_c_vs_arc/"><em>https://dementievmykola.com</em></a><em> on January 19, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19859c22d822" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Erasure in Swift — Simplify using Protocols with Associated Types; any/some vs manual(custom)…]]></title>
            <link>https://medium.com/@mykola.dementiev/type-erasure-in-swift-simplify-using-protocols-with-associated-types-any-some-vs-manual-custom-d6ef3200942c?source=rss-1d0b08a6ac5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ef3200942c</guid>
            <category><![CDATA[associatedtype]]></category>
            <category><![CDATA[some]]></category>
            <category><![CDATA[type-erasure]]></category>
            <category><![CDATA[custom-type-eraser]]></category>
            <category><![CDATA[anies]]></category>
            <dc:creator><![CDATA[Mykola Dementiev]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 15:40:25 GMT</pubDate>
            <atom:updated>2026-02-27T14:21:31.334Z</atom:updated>
            <content:encoded><![CDATA[<h3>Type Erasure in Swift — Simplify using Protocols with Associated Types; any/some vs manual(custom) approaches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Nic3t7ySC62ukscakqIsA.jpeg" /></figure><h3><strong>The Problem: Why Should You Care About Type Erasure?</strong></h3><p>Imagine you’re building a flexible system in Swift, and you decide to use a protocol with an associated type (PAT). After all, relying on abstractions rather than concrete implementations is a cornerstone of good software design — shoutout to <a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a> principles and <a href="https://www.amazon.de/-/en/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164">Uncle Bob’s</a> best practices! For example, you define a protocol like this:</p><pre>protocol InterfaceWithAssociatedType {<br>    associatedtype OurType<br>    func doSomething(with value: OurType)<br>}</pre><p>This approach allows you to design a system that’s modular, testable, and aligned with the <strong>`Dependency Inversion Principle`</strong> (the “D” in SOLID): depending on abstractions rather than concrete details. But here’s the thing — protocols with associated types have their own quirks. Specifically, you’ll quickly realise they don’t play nicely with variables or function parameters without some extra effort. So, how do you bridge the gap between abstraction and implementation? Let’s dive in!</p><p>For example, suppose you want to store an instance of a type conforming to this protocol in a variable or pass it as a function parameter. You’ll immediately run into a problem:</p><pre>struct StringHandler: InterfaceWithAssociatedType {<br>    func doSomething(with value: String) {<br>        print(&quot;Handling string: \(value)&quot;)<br>    }<br>}<br><br>let handler: InterfaceWithAssociatedType = StringHandler() <br>handler.doSomething(with: &quot;Hello, World!&quot;) // Member &#39;doSomething&#39; cannot be used on value of type &#39;any InterfaceWithAssociatedType&#39;; consider using a generic constraint instead</pre><p>So, how do you work around this? Enter <strong>type erasure — a</strong> technique that hides the associated type, allowing you to use the protocol as a type. In this article, we’ll explore two main approaches to type erasure: any and some and manual (custom) type erasure.</p><h3>Approach 1: Using &#39;any’ and &#39;some&#39;</h3><p>Swift provides two powerful tools for working with protocols with associated types: any and some. These keywords allow you to simplify your code while maintaining some level of type safety.</p><p>What Are any and some?</p><p><strong>Any</strong> (Introduced in <em>Swift 5.6</em>) The any keyword allows you to use protocols with associated types as existential types. It essentially tells the compiler, “I don’t care about the specific type; just let me work with any type that conforms to the protocol.”</p><pre>let stringHandler: any InterfaceWithAssociatedType = StringHandler()<br><br>func process(handler: any InterfaceWithAssociatedType) {<br>    // Note: You cannot call `doSomething` directly because `OurType` is unknown.<br>    // You would need to cast or use a wrapper to resolve the type.<br><br>    /* e.g.:  casting <br>    (handler as? StringHandler)?.doSomething(with: &quot;Hello world&quot;)<br>    */<br>}</pre><p>While any solves the immediate issue of storing or passing the protocol, it introduces runtime overhead and limits functionality because the associated type remains unresolved.</p><p><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0335-existential-any.md">Read more about </a><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0335-existential-any.md">any in Swift 5.6 proposal</a></p><p><strong>Some</strong> (Introduced in <em>Swift 5.1</em>) The some keyword allows you to return a specific, opaque type that conforms to a protocol. This ensures type safety at compile time while hiding the concrete type from the caller. You&#39;re likely already familiar with this concept if you&#39;ve worked with SwiftUI&#39;s View protocol.</p><p>Let’s take a look at these code snippets:</p><pre>func createHandler() -&gt; some InterfaceWithAssociatedType {<br>     StringHandler()<br>}<br><br>let handler = createHandler()<br>handler.doSomething(with: &quot;Hello World&quot;) // ERROR: Cannot convert value of type &#39;String&#39; to expected argument type &#39;(some InterfaceWithAssociatedType).OurType&#39;</pre><p>The issue occurs because some hides the associated type (OurType), making it impossible for the compiler to verify that &quot;Hello World&quot; matches the expected type. No way to check that! To fix it, you can either use generics or manual type erasure (we&#39;ll be checking that in upcoming paragraph) to explicitly handle the associated type. Manual type erasure is often the most practical solution in real-world scenarios. Or we can modify our interface to be able to provide the type as associated values. E.g.:</p><pre>protocol InterfaceWithAssociatedType&lt;OurType&gt; { // &lt;- `&lt;OurType&gt;`<br>    associatedtype OurType<br>    <br>    func doSomething(with value: OurType)<br>}<br><br>// without using a generics here we encountered a slight duplication : `...&lt;String&gt;`<br>func process(handler: some InterfaceWithAssociatedTypeNew&lt;String&gt;) {<br>    handler.doSomething(with: &quot;Hello world&quot;)<br>}<br><br>struct StringHandlerNew&lt;TypeNew&gt;: InterfaceWithAssociatedTypeNew {<br>    func doSomething(with value: TypeNew) {<br>        print(&quot;Handling new string: \(value)&quot;)<br>    }<br>}<br><br>let handler = StringHandlerNew&lt;String&gt;()<br>process(handler: handler)<br>// or, simply:<br>handler.doSomething(with: &quot;Direct call&quot;)</pre><blockquote><em>btw, our function</em></blockquote><blockquote><em>func process(handler: some InterfaceWithAssociatedType) { ... }</em></blockquote><blockquote><em>has the same signature as:</em></blockquote><blockquote><em>func process&lt;T: InterfaceWithAssociatedType&gt;(handler: T) { ... }</em></blockquote><blockquote><em>…this seems to be one of the primary reasons why “some” was introduced: simplifying the signature.</em></blockquote><p><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0244-opaque-result-types.md">Read more about </a><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0244-opaque-result-types.md">some in Swift 5.1 proposal</a></p><h3>Approach 2 (why did we all come here): Manual (Custom) Type Erasure</h3><p>If you need full control over your types and want to avoid the limitations of any and some, <strong>manual</strong> type erasure is the way to go. This approach involves creating a wrapper struct or class that conforms to the protocol and hides the associated type.</p><pre>struct AnyInterfaceWithAssociatedType&lt;T&gt;: InterfaceWithAssociatedType {<br>    private let _doSomething: (T) -&gt; Void<br><br>    init&lt;H: InterfaceWithAssociatedType&gt;(_ handler: H) where H.OurType == T {<br>        _doSomething = handler.doSomething<br>    }<br><br>    func doSomething(with value: T) {<br>        _doSomething(value)<br>    }<br>}</pre><p>Now, you can use the type eraser to store or pass handlers:</p><pre>let stringHandlerManualEraser = AnyInterfaceWithAssociatedType(StringHandler())<br><br>func process&lt;T&gt;(handler: AnyInterfaceWithAssociatedType&lt;T&gt;, <br>                value: T) {<br>    handler.doSomething(with: value)<br>}<br><br>process(handler: stringHandlerManualEraser, <br>        value: &quot;Hello World, from manual eraser!&quot;)</pre><p>This approach provides full type safety and flexibility but requires additional boilerplate code.</p><p>If you suddenly noticed that the manual type erasure approach looks a lot like the Decorator pattern — well, you&#39;re absolutely right!</p><p>In essence, what we’re doing here is wrapping the original type in a struct or class that “decorates” it by conforming to the protocol and delegating all the work back to the underlying implementation. It’s like putting a fancy coat on your concrete type to hide its complexity while still letting it do its job. This is exactly what the Decorator pattern is all about: adding a layer of abstraction without changing the core functionality.</p><p>So yeah, manual type erasure isn’t just a Swift trick — it’s also a nod to classic design patterns. Cool, right? 🎩✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyvDkraFAVEhEphT2LbZAA.png" /></figure><h3>Conclusion</h3><p>Protocols with associated types are a powerful feature in Swift, but they come with challenges. Type erasure provides a way to work around these limitations by hiding the associated type.</p><p>Use any and some for simplicity and quick solutions. Use manual type erasure when you need full control and flexibility. By understanding these techniques, you can choose the right approach for your specific use case and avoid common pitfalls when working with PATs.</p><p><strong>P.S.</strong> In many cases, you’ll realise that you probably didn’t intend to use any and can instead make some or a generic work for your needs. According to the Swift team, we should always aim to avoid using any whenever possible. This is because any relies on runtime checks to determine the underlying type, which introduces overhead and potential inefficiencies. On the other hand, when using some, the type is resolved at compile time, making it more efficient and type-safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ef3200942c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>