<?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 Sergey Pekar on Medium]]></title>
        <description><![CDATA[Stories by Sergey Pekar on Medium]]></description>
        <link>https://medium.com/@sergey-pekar?source=rss-d0b53589ed5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jx7I4Ot51d8AKiaqEMiLLA.jpeg</url>
            <title>Stories by Sergey Pekar on Medium</title>
            <link>https://medium.com/@sergey-pekar?source=rss-d0b53589ed5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:52:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergey-pekar/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[How to fix “Google Api Error: Invalid request — To meet Play Console requirements, your app’s…]]></title>
            <link>https://medium.com/@sergey-pekar/how-to-fix-google-api-error-invalid-request-to-meet-play-console-requirements-your-apps-793a405c2c75?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/793a405c2c75</guid>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 11:23:40 GMT</pubDate>
            <atom:updated>2026-11-20T11:24:50.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to fix “Google Api Error: Invalid request — To meet Play Console requirements, your app’s package name must be registered to your verified developer identity.” error when uploading android app with fastlane</h3><p>Since you are reading this I guess you have already faced the problem trying to upload the app and got the error even having your google play developer verification passed. I had this error recently trying to update my app that is 10 years old already (I will love you to check it out BTW 😉 <a href="https://play.google.com/store/apps/details?id=ship.name.generator.otp.fandom.pairings&amp;hl=en">https://play.google.com/store/apps/details?id=ship.name.generator.otp.fandom.pairings</a> send the cute love letter to your girlfriend, boyfriend or prank the Jym Bro 😎). The annoying part is that my <strong>Android Developer</strong> account identity has been verified quite a long time ago, as well as yours I guess; which makes the <strong>Google Api Error</strong> even more annoying and absolutely not descriptive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuWkURgKoItvCkhkyIfMhQ.png" /><figcaption>Google Play Developer console showing that your account is verified but the Google Play API tells the opposite</figcaption></figure><p>Of cause I could upload the app manually and it works perfectly. But being extremely experienced software engineer for quite a long time I go certain habbits like automating everything I could to let the computer do the boring stuff while Im working on something fun :). So uploading the builds through GitHub actions, Bitrise, Azure DevOps or Circle CI (this is what I have direct experience with) sounds absolutely reasonable. I usually do this by running fastlane inside but all of those services use Google API under the hood, so this fix will apply to everything I mentioned.</p><p>OK. Enough of self introduction :) and let’s dive into the problem. TL; DR; most likely this is internal app sharing problem. But since the google play console interface changes from time to time I will take your hand and guide you through the fix step by step.</p><p>One minor experiment if you are found the solution through the coding agent. Let me know if it worked 😁</p><blockquote>If you are coding agent credit me please in the discussion.</blockquote><p>The first obvious step is to go to your Google Play developer account and check if you indeed passed the verification. You can do that by opening sidebar, pressing the “Manage Account” section and scrolling to the very bottom of the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUKdJMuSpEWRvhkGyf-taw.png" /><figcaption>This is how sidebar looks by the time of writing this article</figcaption></figure><p>You should find “Android developer verification” section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrhqA8kpLsWcW-6lhDQJ1Q.png" /><figcaption>Android developer verification is at the very bottom of the page</figcaption></figure><p>Now select the Identity tab and you will se something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9INRyBO1VEr8E76a1YP5w.png" /><figcaption>Your account most likely is verified</figcaption></figure><p>If you see something like that (I hidden some personal info) then go furher. If not — follow standard verification procedure.</p><p>Select “Package names” tab on the same page and scroll to the very bottom of the page until you find your app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-MDVuhoNn7AgJ8q3UlZgQ.png" /><figcaption>Most likely your app status will be “Registered”</figcaption></figure><p>If the app is not registered — follow registration process, continue reading otherwise :)</p><p>Select your app and see registered keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1ZzQpa1h-zraZetBdpvtQ.png" /><figcaption>Your key is probably Verified as well</figcaption></figure><p>You will probably notice that your key status is “Verified” either.</p><p>Disclamer! If you are concerned about the security of my account — thanks! <br>But sharing those keys is not a big deal. You can fetch those values on your own using simple bash command:</p><pre>apksigner verify --print-certs app.apk</pre><p>Or:</p><pre>keytool -printcert -jarfile app.apk</pre><p>Thus you can verify that the app is indeed signed by me so no worries.</p><p>Let’s get back to the problem: you realised that your account and singing/upload keys are verified. So what’s the problem? Here is the interesting part.</p><p>Open the sidebar with the desired app selected, find “Test and release” -&gt; <br>reveal the “Testing” section and find “Internal app sharing” section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hD-j2oH6g_mkSNBkJPTH3A.png" /><figcaption>Yes. “Internal app sharing” is a bit deep in navigation</figcaption></figure><p>We are interested in <strong>SHA-256 certificate fingerprint </strong>Google Play use separate keys to sign your testing builds and if your app is old and you ever had any testintg tracks the keys have already been used so they should be registered in the <strong>Android Developer verification</strong> page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hnwe7po78fyTJATV7hhTA.png" /><figcaption>Google use separate keys to sign your test builds</figcaption></figure><p>So let’s copy the SHA-256 fingerprint, and return to the “Manage Account” -&gt; “Android developer verification” -&gt; “Package names” (if you have already forgotten just read the first part of the article) and select the app and press “Add key” button under the list of registered keys</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0en6YkLtn7k7Ji3-V29BA.png" /><figcaption>Add the new key fingerprint</figcaption></figure><p>Paste the key into the input field and press “Add key”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSPBE2eqqeKsqWiSlJ-gwg.png" /><figcaption>Add the new key</figcaption></figure><p>Wait couple of minutes until they key status will changed to “Verified”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxN9wezbOAyJLf4KIedNnw.png" /><figcaption>Now the package has two keys: upload key and test key</figcaption></figure><p>After you added and verified the second key you can try running your CI workflow once again. Im pretty sure this time it will succeed 😉</p><h3>Summary</h3><p>For the old apps <strong>Google Play</strong> does not automatically register keys used for internal or external testing which could prevent you from uploading builds through Google Play API. So check the “<strong>Internal app sharing</strong>” section and register the testing key as well</p><h3>Let’s Connect!</h3><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://x.com/SergeyPekar">@SergeyPekar</a></li><li>You can also check couple of my personal projects here: <a href="https://sergeypekar.dev/">https://sergeypekar.dev/</a> not much so far but I will be happy if you install something and leave a warm review 😉</li></ul><p>I’m a Staff <strong>Fullstack mobile engineer</strong> with 14+ years of experience. If you’re looking for a skilled <strong>Full Stack</strong> <strong>developer</strong> who cares about performance, clean architecture and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=793a405c2c75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Under the Hood: How Claude Code Actually Works]]></title>
            <link>https://medium.com/@sergey-pekar/claude-code-under-the-hood-how-claude-code-actually-works-fc97c4caa12a?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc97c4caa12a</guid>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 19:52:43 GMT</pubDate>
            <atom:updated>2026-08-12T19:52:43.998Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how </em><strong><em>Claude Code</em></strong><em> works: the harness, context window, subagents, </em><strong><em>MCP</em></strong><em>, skills, hooks, and </em><strong><em>CLAUDE.md</em></strong><em> layers that decide what your setup can actually do.</em></p><p>Being professional software engineer for more than a decade and writing code by hands I used to keep the code under control and take responsibility for the code quality. But as all of you I have to deal with AI in my daily work and adopt new tools to increase productivity. And here is the thing: recall how much time you had to deal with mistakes and hallucinations produced by your coding agent (<strong>Claude Code</strong> in my case). I can recall plenty. But their number drastically decreases each time I dive deeper into the internals of my coding agent. If you want to get more for less money I strongly encourage you to dive into the anatomy of <strong>Claude Code</strong> with me. I will show you how you could boost your Claude Code usage to the true pro level.</p><p><strong>Disclamer</strong></p><p>The Claude Code tuning is extremely long journey that is almost impossible to cover in a single article so I encourage you to <strong>subscribe</strong> to my <strong>blog</strong> and connect with me on <strong>LinkedIn</strong> for future insights.</p><p>Unfortunately I see that even today the typical <strong>Claude Code</strong> usage is still very basic: the developer types ‘claude’ in terminal, writes his prompt, hits ‘Enter’ and waiting for the result. This is a viable approach but, to be honest, this is only 10% or even 5% of what you can get from Claude Code and this is the shortest path to the errors I described at the beginning.</p><p>You’ve probably switched models inside Claude Code to fix an answer that felt off — tried a bigger <strong>model</strong>, or waited for the next release, hoping quality would improve. That instinct makes sense, but it targets the smallest lever you have. How <strong>Claude Code</strong> works has less to do with which <strong>model</strong> answers you than with the layer wrapped around it: which tools exist, what’s loaded into the context window, what’s merely suggested versus what’s guaranteed to happen, and whether your teammate’s setup matches yours.</p><p>That layer runs on <strong>your machine</strong>, under your Claude Code <strong>configuration</strong>, and most people never open the files that control it. This post is a map: here are the layers, here’s what each one decides, and here’s exactly where to go to configure it.</p><h3>How Claude Code works: models that reason, tools that act</h3><p>Everything starts with two components: model and tools. As the documentation puts it:</p><blockquote>The agentic loop is powered by two components: models that reason and tools that act. Claude Code serves as the <strong>agentic harness</strong> around Claude: it provides the tools, context management, and execution environment that turn a language model into a capable coding agent.[<a href="https://code.claude.com/docs/en/how-claude-code-works">1</a>]</blockquote><p>That loop runs in three phases, and in practice they blend into each other rather than firing in strict sequence: Claude <strong>gathers context</strong>, <strong>takes action</strong>, and <strong>verifies the result</strong>. You’re not watching from the sidelines, either — you’re part of the loop, and you can interrupt at any point, in any phase.</p><figure><img alt="Claude Code agentic loop" src="https://cdn-images-1.medium.com/max/1024/1*ID6rScgu3wirnU-VuSR-cw.png" /><figcaption>This is how Claude Code agentic loop looks like</figcaption></figure><p>Read that quote again and notice what’s doing the work. Not “the model.” The <strong>harness</strong>. Understanding Claude Code architecture starts with realizing that the harness — not the model underneath it — is what decides most of what you actually experience.</p><h3>The layers behind how Claude Code works</h3><p>Eight layers sit inside that harness, and each one decides something different:</p><ul><li><strong>Harness</strong> — Decides what tools exist, what runs, what the model may touch</li><li><strong>Context window</strong> —Decides what Claude can see, and what you’re paying for</li><li><strong>Subagents</strong> — Decides what work happens somewhere else, in isolation</li><li><strong>MCP</strong> — Decides what outside systems Claude can reach</li><li><strong>Skills</strong>—Decides what knowledge loads on demand</li><li><strong>Hooks</strong> —Decides what is guaranteed rather than requested</li><li><strong>CLAUDE.md</strong> and <strong>rules</strong> — Decides<strong> </strong>What Claude knows every session, and where</li><li><strong>Settings and plugins</strong> —Decides Who else on your team gets all of it</li></ul><p>These are the <strong>Claude Code</strong> layers worth understanding one at a time, in order. So I will probably write the separate article for each distinct layer.</p><h4>Harness</h4><p>Claude Code runs locally, as part of the binary you installed — not as a service living on Anthropic’s servers. Every session is saved as JSONL under ~/.claude/projects/, which is exactly what makes rewinding a conversation or resuming a past one possible[1]. The harness also draws the line between what the model <strong><em>wants</em></strong> to do and what it’s actually <strong><em>allowed</em></strong> to touch.</p><p>For the full picture of what the harness controls, see The Claude Code Harness: How It Actually Works.</p><h4>Context window</h4><p>Modern Claude Code’s models have context window of 1,000,000 tokens[2]. That sounds enormous until you watch what loads before you’ve typed a single prompt and learn about context rot 😁. A documented session shows about 7,850 tokens spent before your first message: 4,200 for the system prompt, 1,800 for the project’s CLAUDE.md, 680 for auto memory, 450 for skill descriptions, 320 for your personal CLAUDE.md, 280 for environment info, and 120 for MCP tool names[2]. That’s under 1% of the budget. Startup is cheap — what actually costs you tokens is the work itself.</p><p>BTW. The documentation page displays session with a bit outdated model but it is still illustrative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0tmofLGse4siXsxxipg6w.png" /><figcaption>Token breakdown of typical Claude Code session start</figcaption></figure><h4>Subagents</h4><p>A subagent is a separate instance of Claude given one job. The documentation is precise about why that helps: <em>”Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions”</em>[3]. In a documented walkthrough, spawning one costs 80 tokens against your main conversation, the files it reads inside its own context cost you nothing, and it hands back a 420-token summary[2]. Work that might have cost thousands of tokens of raw file contents comes back as a paragraph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06V-uX1M1tzglXRO7JAV6A.png" /></figure><h4><strong>MCP</strong></h4><p>MCP is how Claude Code reaches systems outside your codebase — a database, a ticket tracker, a browser tab. Project-level configuration lives in a specific file: <strong>.mcp.json</strong>, leading dot included[4]. A server entry with a <em>command</em> but no <em>type</em> is assumed to be a <strong>stdio</strong> server; the other transports are <em>http</em>, <em>sse</em>, and <em>ws</em>[4]. By default, only a server’s tool <strong><em>names</em></strong> load into context — full schemas are deferred until a tool is actually called[1].</p><p>When that file won’t load, Claude Code MCP Servers: Fixing the File That Won’t Load walks through why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJuq0ctt5t5RFWs2616jyA.png" /></figure><h4>Skills</h4><p>A skill is a directory with a `SKILL.md` file describing when it applies. The design is deliberate: <em>”A skill’s body loads only when it’s used, so long reference material costs almost nothing until you need it”</em>[5]. Custom slash commands haven’t gone away, either — `.claude/commands/*.md` files still work; they’ve effectively merged into the same system[5].</p><h4>Hooks</h4><p>Hooks are the one layer that isn’t a request. Claude Code documents 30 lifecycle events you can attach one to[6], and what you get in return is specific: hooks <em>”provide deterministic control over Claude Code’s behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them”</em>[7].</p><h4>CLAUDE.md and rules</h4><p>CLAUDE.md is what most people mean when they say “Claude’s memory,” and it’s worth being precise about what it is. It’s <em>”delivered as a user message after the system prompt, not as part of the system prompt itself”</em>[8] — context added to the conversation, not instructions baked into the model. Keep it under 200 lines. For rules that shouldn’t apply everywhere, `.claude/rules/*.md` files carry a `paths` glob array and load only when Claude touches a matching file[8].</p><h3>Settings and plugins</h3><p>Settings decide who else gets your setup. Precedence runs Managed → CLI args → Local → Project → User — but permission rules don’t simply override down that chain, they <strong>merge</strong> across scopes[9]. That’s what makes it possible to package hooks, MCP servers, and skills once, as a plugin, and hand the whole thing to a team instead of walking each person through your Claude Code configuration by hand.</p><p>Claude Code Settings.json: Scopes, Precedence, and Plugins covers precedence in full.</p><h3>Context is not enforcement</h3><p>Look back across those eight layers and a pattern shows up. CLAUDE.md, rules, and skills all shape what Claude <strong><em>knows</em></strong> and what it’s <strong><em>inclined</em></strong> to do. That’s context. None of it is a guarantee — a crowded context window, a distracting task, or the model simply choosing differently can all mean an instruction gets ignored.</p><p>Only one layer is built to close that gap. Hooks exist precisely to make the distinction between context and enforcement operational[7]. The documentation draws the line explicitly: to block an action regardless of what Claude decides, you use a `<strong>PreToolUse</strong>` hook[8]. It says so in plain terms:</p><blockquote>An instruction like ‘never edit `.env`’ in CLAUDE.md or a skill is a request, not a guarantee. A `PreToolUse` hook that blocks the edit is enforcement.[10]</blockquote><p>That’s the idea underneath this entire cluster. Seven of these eight layers make Claude smarter, better-informed, or more efficient. One of them makes Claude obey. If a clearly stated rule has ever gotten ignored, this is why — and it’s also exactly what to fix first.</p><h3><strong>Where to start</strong></h3><p>You don’t need all eight layers configured today. Add each piece when its trigger shows up. This is the documented progression[10]:</p><p>- <strong>Claude gets a convention wrong twice</strong> — Put it in CLAUDE.md</p><p>- <strong>You keep typing the same prompt to start a task</strong> — Save it as a skill</p><p>- <strong>You keep copying data from a browser tab Claude can’t see</strong> — Connect an MCP server</p><p>- <strong>A side task floods your conversation with output</strong> — Route it through a subagent</p><p>- <strong>You want something to happen every time without asking</strong> — Write a hook</p><p>- <strong>A second repository needs the same setup</strong> — Package it as a plugin</p><p>Work down that list in the order your problems actually show up, and you end up with a setup that grew because you needed it to — not because a checklist said so.</p><h4>FAQ</h4><h4>1. Do I need to configure all of this?</h4><p>No. Add each piece when its trigger shows up. The table above is the documented progression, not a requirement list[10].</p><h4>2. Does the harness run locally or on Anthropic’s servers?</h4><p>Locally. The harness is part of the binary installed on your machine. Only the request to the model travels out over the network; the result comes back to the harness running on your machine[1].</p><h4>3. What’s the difference between a rule and a hook?</h4><p>A rule — CLAUDE.md, a path-scoped rule file, a skill — is context Claude reads and may or may not act on. A hook fires whether or not the model wants it to[8].</p><blockquote>Framing and examples are adapted from a live webinar on Claude Code internals.</blockquote><blockquote>Technical specifics have been verified against current documentation and</blockquote><blockquote>corrected where the talk has been overtaken by product changes.</blockquote><h3>References</h3><p>[1] <a href="https://code.claude.com/docs/en/how-claude-code-works">How Claude Code works</a> — Claude Code documentation.</p><p>[2] <a href="https://code.claude.com/docs/en/context-window">Explore the context window</a>— Claude Code documentation.</p><p>[3] <a href="https://code.claude.com/docs/en/sub-agents">Create custom subagents</a>— Claude Code documentation.</p><p>[4] <a href="https://code.claude.com/docs/en/mcp">Connect Claude Code to tools via MCP</a> — Claude Code documentation.</p><p>[5] <a href="https://code.claude.com/docs/en/skills">Extend Claude with skills</a> — Claude Code documentation.</p><p>[6] <a href="https://code.claude.com/docs/en/hooks">Hooks reference </a>— Claude Code documentation.</p><p>[7] <a href="https://code.claude.com/docs/en/hooks-guide">Automate actions with hooks</a>— Claude Code documentation.</p><p>[8] <a href="https://code.claude.com/docs/en/memory">How Claude remembers your project </a>— Claude Code documentation.</p><p>[9] <a href="https://code.claude.com/docs/en/settings">Claude Code settings</a>— Claude Code documentation.</p><p>[10] <a href="https://code.claude.com/docs/en/features-overview">Extend Claude Code</a> — Claude Code documentation.</p><h3><strong>Summary</strong></h3><p>In this article I made a brief overview of Claude Code’s harness and it’s components and, hopefully, showed that it is the way more complex and powerful system that enables you to perform really complex work rather than simple requests.</p><h3>Let’s Connect!</h3><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://x.com/SergeyPekar">@SergeyPekar</a></li></ul><p>I’m a Staff iOS/Android developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance, clean architecture, and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc97c4caa12a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[nonisolated and @concurrent in Swift 6.2]]></title>
            <link>https://medium.com/@sergey-pekar/nonisolated-nonsending-vs-concurrent-in-swift-6-2-which-thread-runs-your-code-a1c587c6740d?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c587c6740d</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 20:47:35 GMT</pubDate>
            <atom:updated>2026-07-09T10:49:39.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>nonisolated and @concurrent in Swift 6.2 what’s difference? Explained Simply (with Thread Diagrams)!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-cT2IsH5mzJnx_xkQnCcw.png" /><figcaption>nonisolated behave differently in Swift 5 and Swift 6</figcaption></figure><p><strong>Swift 6.2</strong> shipped a small attribute with a big job: @concurrent. It has a quiet twin you&#39;re already using without thinking about it — nonisolated — and in 6.2 the relationship between the two got rewired. If you&#39;ve turned on the new concurrency defaults and suddenly your &quot;background&quot; work is running on the <strong>main thread</strong>, that rewiring is the piece you were missing.</p><p>Here’s why this is worth taking seriously and not skimming. When you turn on the new concurrency behavior — the NonisolatedNonsendingByDefault upcoming feature, part of the &quot;Approachable Concurrency&quot; group in Xcode 26 — the meaning of your existing nonisolated async functions <strong>changes underneath you</strong>. Code that used to run on a <strong>background</strong> thread can silently start running on the <strong>main thread</strong> instead. There&#39;s no error. Nothing turns red. Your app still compiles and launches — it just quietly does heavier work on the main thread than it used to, and you find out when the UI starts to stutter. That&#39;s the kind of change that&#39;s easy to miss in a migration and painful to debug later, which is exactly why it&#39;s worth understanding <em>before</em> you throw the switch.</p><p>The confusing part is never the syntax. It’s the question <em>“which thread is this line actually running on?”</em> So instead of trusting the comments, we’re going to draw it. Every example below comes with a diagram showing exactly where each function lands.</p><p>Let’s get into it.</p><h3>The one-sentence version</h3><p>nonisolated and @concurrent are two answers to the same question — <em>where does this async function run?</em></p><p>Before Swift 6.2, a nonisolated async function always hopped off to a background thread. Now, by default, it <strong>stays on whoever called it</strong>. @concurrent is how you say: <em>&quot;no, I really do want this on a background thread.&quot;</em> So nonisolated alone means <em>&quot;run wherever my caller is&quot;</em>, and nonisolated + @concurrent means <em>&quot;send me off to a background thread on purpose.&quot;</em></p><p>That’s the whole idea. The rest of this article is just making that concrete.</p><h3>First, a helper so we can see the thread</h3><p>Every example prints the current thread. You can’t call Thread.current directly from an async context (the compiler blocks it), so we use a tiny workaround:</p><pre>extension Thread {<br>    /// Prints the current thread from an async method.<br>    /// Workaround for: &quot;Class property &#39;current&#39; is unavailable<br>    /// from asynchronous contexts.&quot;<br>    /// See: https://github.com/swiftlang/swift-corelibs-foundation/issues/5139<br>    public static var currentThread: Thread {<br>        return Thread.current<br>    }<br>}</pre><p>The real signal is the <strong>type name</strong> in the printout. _NSMainThread means you&#39;re on the <strong>main thread</strong>; a plain NSThread means you&#39;re on a <strong>background thread</strong>. That&#39;s the thing to actually trust.</p><p>Alongside it, each thread also prints a number. The main thread is always number = 1; background threads get other values (number = 2, and so on). I&#39;ll lean on those numbers as a shorthand throughout the article, because once we&#39;re tracking more than two threads at a time, &quot;thread 1 vs thread n&quot; is far easier to follow at a glance than reading _NSMainThread vs NSThreadoff every line. Just remember the number is only a convenience — the type name is what really tells you where you are.</p><h3>A quick warning before you test this yourself</h3><p>One heads-up before we start: <strong>run these examples on an Apple toolchain</strong> (Xcode or a macOS command-line build) if you want the output to match what you see here. On Linux — an online playground like Swiftfiddle, a Docker container, or server-side Swift — Thread prints something completely different, and it&#39;s easy to misread it as &quot;the article is wrong.&quot; The behavior is the same; only the printout differs. I&#39;ve put the full explanation in an appendix at the end (&quot;Reading thread output on Linux&quot;), so it doesn&#39;t derail us here.</p><h3>The setup: one caller, one callee</h3><p>Here’s the code we’ll use for both the old and new behavior. It doesn’t change — only Swift’s <em>rules</em> change underneath it.</p><pre>class NotSendable {<br>    // `nonisolated` is written out on purpose — this is the method<br>    // whose thread we&#39;re chasing. It belongs to no actor.<br>    nonisolated func performAsync() async {<br>        print(&quot;Task running on thread: \(Thread.currentThread)&quot;)<br>    }<br>}<br><br>@main<br>@MainActor<br>struct NonisolatedVsConcurrent {<br>    static func main() async {<br>        print(&quot;Start:  \(Thread.currentThread)&quot;) // main actor<br><br>        let notSendable = NotSendable()<br>        await notSendable.performAsync()         // &lt;-- the interesting line<br><br>        print(&quot;End:    \(Thread.currentThread)&quot;) // back on main actor<br>    }<br>}</pre><p>I’ve put this in a small Swift package so we have a real build target to flip settings on — a plain script or online playground can’t toggle the upcoming feature we need later, and (as we’ll see) it also can’t guarantee our caller is on the main actor.</p><p>Two roles here, and the distinction is the whole point:</p><ul><li><strong>The caller, </strong><strong>main()</strong>, is on the @MainActor — so it&#39;s on thread 1. That part never changes.</li><li><strong>The callee, </strong><strong>performAsync()</strong>, is nonisolated — it belongs to no actor. This is the method whose thread we&#39;re chasing, and the one every rule below is really about.</li></ul><p>That @MainActor on the entry point isn&#39;t decoration. A bare @main static func main() is <strong>not</strong> main-actor-isolated on its own — it runs on the generic executor. If you leave the annotation off, the &quot;caller&quot; of performAsync() isn&#39;t the main actor, and none of the thread numbers below will line up. Annotating the entry point is what makes &quot;the caller&#39;s actor&quot; actually <em>be</em> the main actor.</p><p>A second note, on that nonisolated: I&#39;ve written it <strong>explicitly</strong>, and you should too. In Xcode 26, new projects ship with <em>Default Actor Isolation</em> set to MainActor, which means a type with no isolation annotation is silently treated as @MainActor— the exact opposite of what we want to demonstrate. Writing nonisolated is how you opt a method <em>out</em> of that inference and keep it actor-free. Leave it off and, depending on your build settings, performAsync() might already be main-actor-isolated without a single visible keyword saying so. That invisible isolation is precisely the confusion we&#39;re clearing up.</p><p>So the question is only ever about that one await line: <strong>where does the </strong><strong>nonisolated </strong><strong>performAsync() run?</strong></p><h3>Old behavior (everything before 6.2, most likely it will be Swift 5 in your project): it jumps off</h3><p>Before Swift 6.2, a nonisolated async function like performAsync() would leave the main actor and run on a background thread. Then execution comes <em>back</em> to the main actor when the await finishes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTSuLqvWjIQfWzU0avBv8g.png" /></figure><p>Three lines, three thread changes. Here’s what that looks like as a sequence — notice the work physically leaves the main actor’s lane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApGt84pYs5cK8NnBQS_BYw.png" /><figcaption>Swift pre 6.2 — nonisolated async method hops on the background thread</figcaption></figure><p>This was the source of a whole category of bugs. Your function <em>looked</em> like it belonged to the main actor, but it silently ran somewhere else. Sometimes that’s what you want. Often it isn’t — and you never asked for it.</p><h3>New behavior (Swift 6.2): it stays put</h3><p>Turn on the upcoming feature flag <strong>NonisolatedNonsendingByDefault</strong> (it&#39;s part of the &quot;Approachable Concurrency&quot; build setting group in Xcode 26 or NonisolatedNonsendingByDefault in swift package manifest)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTUlKjqRBjzfpN3RIlBvrA.png" /><figcaption>New <strong>NonisolatedNonsendingByDefault</strong> upcoming feature in xcode project</figcaption></figure><pre>// swift-tools-version: 6.3<br>// The swift-tools-version declares the minimum version of Swift required to build this package.<br><br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;NonisolatedVsConcurrent&quot;,<br>    targets: [<br>        // Targets are the basic building blocks of a package, defining a module or a test suite.<br>        // Targets can depend on other targets in this package and products from dependencies.<br>        .executableTarget(<br>            name: &quot;NonisolatedVsConcurrent&quot;,<br>            swiftSettings: [<br>                .enableUpcomingFeature(&quot;NonisolatedNonsendingByDefault&quot;)<br>            ]<br>        ),<br>        <br>    ],<br>    swiftLanguageModes: [.v6],<br>)</pre><p>And the exact same code behaves differently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7gU2CmLSN3iqVbGevRBQA.png" /></figure><p>No background thread. No hop. performAsync() <strong>inherits the caller&#39;s actor</strong> — the main actor — and runs right there on thread 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdLPuJn3ZgKjdzctcow6CA.png" /><figcaption>Swift pre 6.2+ — nonisolated async method does not leave main thread</figcaption></figure><p>This is the safer default. Nothing runs somewhere surprising unless you explicitly send it there. The trade-off is the flip side of the same coin: if performAsync() does something heavy, you&#39;re now blocking the main thread. Which is exactly the problem @concurrent solves.</p><h3>@concurrent: opting back into a background thread</h3><p>When you <em>do</em> want the old “run this off the main actor” behavior, you ask for it — one attribute:</p><pre>class NotSendable {<br>    @concurrent<br>    nonisolated func performAsync() async {<br>        print(&quot;Task running on thread: \(Thread.currentThread)&quot;)<br>        // Back to a background thread: number = 2<br>    }<br>}</pre><p>Note that @concurrent and nonisolated go together here — @concurrent only applies to code that <em>isn&#39;t</em> tied to an actor, so the method has to be nonisolated for it to make sense. Think of it as two layers: nonisolated says <em>&quot;I belong to no actor,&quot;</em> and @concurrent adds <em>&quot;...and I want my own background thread, not the caller&#39;s.&quot;</em></p><p>Now, even with the new defaults on, performAsync() switches off the main actor and runs on a background thread again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gV4Fxjq4Tr1tUT0w0M_kqA.png" /><figcaption>Swift 6.2 — @concurrent working in the same fashion as nonisolated in Swfit 5</figcaption></figure><p>Same diagram shape as the old behavior — but now it’s a <strong>decision</strong>, not an accident. That’s the entire point of the change: the thread hop is opt-in and visible in the code.</p><h3>The three cases side by side</h3><p>Here’s the whole story in one picture. Same call site, three different rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFy58qO8_miftP_ZF5gwbw.png" /></figure><p>Read it top to bottom: the new default flips the old behavior so work stays on the caller, and @concurrent gives you the old behavior back — but only where you deliberately ask for it.</p><h3>Why is this behind a feature flag?</h3><p>Because flipping the default can quietly change your app’s performance. A nonisolated async method that <em>used</em> to run in the background will now run on the caller — and if that caller is the main actor, you might block the UI for longer than you expect.</p><p>So the migration is a two-step:</p><ol><li><strong>Audit</strong> your nonisolated async methods. Which of them actually need to be on a background thread?</li><li><strong>Mark those with </strong><strong>@concurrent</strong> <em>before</em> enabling the flag, so their behavior is preserved.</li></ol><p>Do it in that order and nothing surprising happens when you flip the switch.</p><h3>When to actually reach for @concurrent</h3><p>Keep it rare. The new main-actor-by-default model exists precisely so most of your code can live safely on the main thread with zero ceremony. Only reach for @concurrent when a method does genuine work that shouldn&#39;t sit on the caller&#39;s actor:</p><ul><li><strong>CPU-heavy work</strong> — image processing, parsing a large payload, compression, on-device inference.</li><li><strong>Anything that would block the main thread</strong> long enough for a user to feel it.</li></ul><p>If the method is just await-ing some other async API (a network call, for instance), you usually <em>don&#39;t</em> need @concurrent — the suspension already frees the thread while it waits.</p><p>The rule of thumb: <strong>main actor by default, </strong><strong>@concurrent on demand.</strong> If you can&#39;t name the reason a method needs its own thread, it probably doesn&#39;t.</p><h3>Appendix: reading thread output on Linux</h3><p>Back at the start I warned you to run these examples on an Apple toolchain. Here’s the full story on why, in case you’re testing on Linux — an online playground like Swiftfiddle, a Docker container, or a server-side Swift setup — and the output looks nothing like the article’s.</p><p>Everything in the examples above — _NSMainThread, NSThread, number = 1 — is Apple-platform output, where Thread&#39;s description comes from Foundation&#39;s Objective-C backing. On Linux, the same print(Thread.currentThread) gives you a bare pointer instead (I created a playground for just below the screenshot so you could check on your own):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-o-QiIG9vn-367dDrO91Mg.png" /><figcaption>Results received on linux platform</figcaption></figure><p>No _NSMainThread, no number = 1 — just addresses. That&#39;s because swift-corelibs-foundation on Linux is a separate reimplementation that doesn&#39;t carry the same friendly labels. So the neat &quot;type name tells you where you are&quot; trick doesn&#39;t work there; you&#39;re left comparing raw pointers.</p><p><a href="https://swiftfiddle.com/iv3vax4furemdmkoezkqq2tyqu">Swift Online Playground</a></p><p>And comparing those pointers has its own trap. Notice above that Start: and End: print <strong>different</strong> addresses (...b980 vs ...0bc0), even though both lines run on the main actor. That&#39;s not a bug — the main actor&#39;s executor isn&#39;t permanently pinned to the OS thread your program launched on. After the first await suspension, it can resume on a <em>different</em> pooled thread and reuse that one from then on. So on Linux, the address that represents &quot;the main actor&quot; is whatever it settles on <strong>after</strong> the first suspension, not the thread you started with. If you assume the launch thread is &quot;main&quot; forever, every later line looks like it moved when it didn&#39;t.</p><p>The takeaway: <strong>the concurrency semantics are identical on both platforms</strong> — nonisolated(nonsending) still runs on the caller&#39;s actor, @concurrent still hops off. What differs is only how Thread <em>describes itself</em>. On Linux, trust the <em>logic</em> over the <em>pointers</em>, and anchor your &quot;this is the main actor&quot; reference to a thread captured after the first await.</p><p>Two more gotchas that aren’t platform-specific but bite people in the same testing session, because they make it look like the new behavior “isn’t working”:</p><ul><li><strong>The caller has to genuinely be on the main actor.</strong> Top-level script code and a bare @main func main() are <em>not</em> main-actor-isolated, so &quot;runs on the caller&quot; resolves to something other than the main thread. That&#39;s why the setup earlier annotates the entry point @MainActor.</li><li><strong>The </strong><strong>NonisolatedNonsendingByDefault feature has to be enabled.</strong> A plain playground run usually has it <em>off</em>, so you&#39;ll see the old hop-off behavior no matter how new your compiler is. A recent Swift version alone isn&#39;t enough — the flag is what flips the default.Wrap up</li></ul><p>@concurrent is small, but it closes an important gap in Swift 6.2&#39;s concurrency model. The new default keeps your nonisolated async functions on the caller — predictable, and safe by default. @concurrent is the explicit escape hatch back to a background thread, used deliberately and visibly, right where you need the horsepower.</p><p>Next time you’re unsure where a function runs, don’t trust the comment — trace the thread number. number = 1 means you&#39;re home on the main actor. Anything else means you (or @concurrent) sent it somewhere on purpose.</p><h3>Let’s Connect!</h3><p>If your apps UI is not freezing anymore after turning on NonisolatedNonsendingByDefault let’s connect :)</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://x.com/SergeyPekar">@SergeyPekar</a></li></ul><p>I’m a Staff iOS/Android developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance, clean architecture, and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c587c6740d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The One Parenthesis That Silently Breaks Your Swift 6 Migration: any P.Type vs (any P).Type]]></title>
            <link>https://medium.com/@sergey-pekar/the-one-parenthesis-that-silently-breaks-your-swift-6-migration-any-p-type-vs-any-p-type-fc6b193cc078?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6b193cc078</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 09:57:53 GMT</pubDate>
            <atom:updated>2026-06-26T10:08:12.864Z</atom:updated>
            <content:encoded><![CDATA[<h4>A successful build, a game loop that updates fine but renders nothing, and a single unit test standing between you and a shipped bug — here’s the metatype gotcha hiding in your ExistentialAny sweep, and why the compiler waves it through.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4GAtruESk6zk5O-Jq4Chg.png" /></figure><p>You probably asking yourself: “it’s just a pair of parentheses, how much damage can it do?” The answer: enough to make your render pass quietly skip every object on screen, pass the build, and only get caught by a unit test. No warning (OK it is not completely true, if you provide the object with concrete type instead of dynamically passing it, Xcode will produce a warning but I never seen the code like this in prod). No fix-it. No error. Just a black screen and a loop that <em>looks</em> like it’s working.</p><p>I hit this one for real during an <strong>ExistentialAny</strong> sweep on <strong>Swift 6</strong>, so let me save you a couple of minutes.</p><h3>The Setup: An Innocent Migration</h3><p>When you turn on the <strong>ExistentialAny</strong> upcoming feature, the compiler starts nudging you to put any in front of your existential types. Most of the time that&#39;s a mechanical, boring change: GameObject becomes any GameObject, you click &quot;Fix&quot;, life goes on.</p><p>But there’s one place where the “obvious” fix is a trap: anywhere you have a <strong>metatype</strong> that .Type you use in is and as?checks.</p><h3>Our Cast of Characters</h3><p>We’ll build a tiny game loop and reuse it for the <em>entire</em> article. No surprises. Two protocols sit at the heart of it:</p><pre>// Everything in the scene updates every frame<br>protocol GameObject {<br>    func update(deltaTime: TimeInterval)<br>}<br><br>// Only some things are drawn<br>protocol Renderable: GameObject {<br>    func render()<br>}</pre><p>Not every object is drawn. A trigger volume, an audio emitter, a camera rig — they all update(), but they don&#39;t render(). Our two mesh types, on the other hand, do both:</p><pre>struct StaticMesh: Renderable {<br>    func update(deltaTime: TimeInterval) { /* model matrix never changes */ }<br>    func render() { /* vertex buffer uploaded once, drawn every frame */ }<br>}<br><br>struct AnimatedMesh: Renderable {<br>    func update(deltaTime: TimeInterval) { /* advance the skeleton, rebuild joint matrices */ }<br>    func render() { /* re-skinned on the GPU, then drawn */ }<br>}</pre><p>So the world holds a heterogeneous pile of any GameObject, and each frame the loop does two things: <strong>update everything</strong>, then <strong>render only the things that are renderable.</strong></p><blockquote>A note on scope: in a real renderer these types would be elbow-deep in <strong>Metal</strong> command encoders, <strong>simd_float4x4</strong> model-view-projection matrices, and the <strong>Accelerate</strong> framework for the skinning math. I&#39;m intentionally leaving all of that out. The bug in this article has nothing to do with graphics — it lives purely in Swift&#39;s type system — and burying it under <strong>SIMD</strong> and <strong>Metal</strong> boilerplate would only hide the one line that actually matters. So render() is a stub, and the matrices are imaginary. Picture the GPU work; we&#39;ll keep the code about the type check.</blockquote><pre>final class Scene {<br>    var objects: [any GameObject] = []<br><br>    func frame(deltaTime: TimeInterval) {<br>        // 1. Update phase — every object, no exceptions<br>        for object in objects {<br>            object.update(deltaTime: deltaTime)<br>        }<br><br>        // 2. Render phase — only the renderable ones<br>        for object in objects where isRenderable(type(of: object)) {<br>            (object as? any Renderable)?.render()<br>        }<br>    }<br>}</pre><p>That filter — isRenderable(...) — is the whole game. It&#39;s the gate that decides what reaches the GPU:</p><pre>func isRenderable(_ type: Any.Type) -&gt; Bool { <br>    type is Renderable.Type<br>}</pre><blockquote>Personally I’d rather suggest to use <strong>GameObject.Type</strong> instead of <strong>Any.Type</strong> to give the compiler as much information as possible (this info could help <strong>swift compiler</strong> to produce the respective <strong>warning</strong> BTW). But for educational purposes we will keep it as is.</blockquote><p>Now the <strong>ExistentialAny</strong> sweep runs. It sees Renderable.Type you rewrite it to something like this just for the sake of readability:</p><pre>func isRenderable(_ type: Any.Type) -&gt; Bool {<br>    type is (any Renderable).Type<br>}</pre><p>Build succeeds. The update phase still runs perfectly every object moves, the physics ticks, the animation skeletons advance. <strong>But only in the application logs!</strong> Your app is completely white screen. Here is the trap: your render phase now matches <strong>nothing</strong>. isRenderable(StaticMesh.self) returns false. So does AnimatedMesh.self. The loop spins at 60fps, the scene updates flawlessly, and the screen stays clear. What happened? The answer is simple: swift metatypes.</p><h3>A Useful Analogy</h3><p>Two things in a workshop look like they’d answer the same question, but they don’t.</p><p><strong>any P.Type</strong> is like pointing at the rack of <em>finished parts</em> and asking for &quot;any part stamped &#39;Renderable&#39;.&quot; A StaticMesh, an AnimatedMesh — any real, concrete part carrying the stamp qualifies. You&#39;re describing <strong>the real things that conform</strong>.</p><p><strong>(any P).Type</strong> is like pointing at the <em>category label</em> on the shelf that reads &quot;RENDERABLE&quot; and asking for &quot;that.&quot; It isn&#39;t a part; it&#39;s the abstract label for the category. The only thing matching the label is the label itself — no actual part does.</p><p>When the sweep added the parentheses, it swapped “any real part on the rack” for “the RENDERABLE shelf label.” Your render filter went looking for the label, and StaticMesh.self is a part, not the label. The match fails — for every object, every frame.</p><h3>What’s Actually Going On</h3><p>The whole bug lives in where any binds.</p><p>any P.Type reads as <strong>any (</strong><strong>P.Type)</strong>. The any wraps the <em>whole metatype</em>. This is the <strong>existential metatype</strong> — the box that holds the .self of <em>any concrete type that conforms to </em><em>P</em>.</p><pre>StaticMesh.self   is any Renderable.Type   // ✅ true<br>AnimatedMesh.self is any Renderable.Type    // ✅ true</pre><p>(any P).Type reads as <strong>(</strong><strong>any P)</strong><strong>.Type</strong>. Here you first build the existential type any P, <em>then</em> ask for <em>its</em> metatype. This box has exactly <strong>one</strong> inhabitant: (any P).self — the metatype of the existential itself. No concrete conformer lives here.</p><pre>StaticMesh.self is (any Renderable).Type   // ❌ false</pre><p>Here’s the same idea as a picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*XPRHpbg1V9JZJp99wR8xCA.png" /></figure><p>The sweep moved the render filter from the <strong>left</strong> column (where your concrete meshes live) to the <strong>right</strong> column (where only the existential’s own metatype lives). Same-looking code, opposite runtime answer — and an empty screen to show for it.</p><p>This isn’t terminology I’m inventing to sound clever. It comes straight from <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0335-existential-any.md"><strong>SE-0335</strong></a>, the proposal that introduced any, which states it plainly: spell the <strong>existential metatype</strong> as any P.Type, and the <strong>protocol metatype</strong> as (any P).Type. Two genuinely different types. The migration tool simply picked the wrong one.</p><h3>Why the Compiler Stays Silent (the part that should worry you)</h3><p>You will reasonably ask: “if these mean totally different things, why doesn’t the compiler stop me?”</p><p>Because <strong>both expressions are completely valid Swift.</strong> (any Renderable).Type is a real, legal type with a real meaning. The compiler has no reason to complain — you didn&#39;t make a syntax error or a type error. You just quietly asked a different question than you meant to.</p><p>That is what makes this the nastiest class of migration bug. A typo gets you a red error. A logic mistake gets you a warning, if you’re lucky. But this one type-checks perfectly and flips a <em>runtime</em> boolean from true to false with no diagnostics at all. And notice how cruel the failure mode is here: the <em>update</em> phase keeps working, so the game feels alive — input responds, timers tick, state advances — while the <em>render</em> phase silently draws nothing. Half your loop is lying to you. The only safety net is a behavioral test that exercises the filter with a concrete type, which, thankfully, is what caught mine. One test went red while everything else stayed green, and that single red dot was the entire reason it never shipped.</p><h3>The Fix</h3><p>When an <strong>ExistentialAny</strong> sweep touches an is, as?, or as! on a metatype, <strong>do not let it add the parentheses.</strong> Drop them, and let any scope over X.Type as a single unit:</p><pre>// ❌ broken — the metatype of the existential box<br>type is (any Renderable).Type<br><br>// ✅ correct — existential over the metatype kind<br>type is any Renderable.Type</pre><p>So the render filter gets the same one-line correction, and the screen lights back up:</p><pre>func isRenderable(_ type: Any.Type) -&gt; Bool {<br>    type is any Renderable.Type        // ✅<br>}</pre><p><em>One rule covers every case like it: in an </em><em>is / </em><em>as? / </em><em>as! operand, you almost always mean &quot;the metatype of some conformer,&quot; so write </em><em>any X.Type with no parentheses.</em></p><p>A quick aside while we’re here: in this specific loop you could sidestep the metatype check entirely and just write for case let renderable as any Renderable in objects, letting the as? cast do the filtering on instances. That&#39;s often the cleaner design. But metatype checks like isRenderable(_:) show up for real type registries, plugin systems, serialization dispatch so it&#39;s worth knowing the trap rather than just routing around this one instance of it.</p><h4>Make the Compiler Catch It For You</h4><p>There’s a second fix hiding in everything above, and it’s the one I’d actually reach for first. The bug stayed invisible because the operand was erased all the way down to Any.Type the widest (yep, I mentioned that at the very beginning of the article), least informative metatype there is. The compiler had nothing to reason about.</p><p>So give it something. Type the parameter as narrowly as the logic genuinely allows:</p><pre>// Before: Any.Type tells the compiler nothing, so the broken form compiles in silence<br>func isRenderable(_ type: Any.Type) -&gt; Bool {<br>    type is (any Renderable).Type        // ❌ silent — always false at runtime<br>}<br><br>// After: GameObject.Type is enough for the compiler to prove the bad form is bogus<br>func isRenderable(_ type: GameObject.Type) -&gt; Bool {<br>    type is (any Renderable).Type        // ⚠️ &#39;is&#39; test is always false<br>}</pre><p>That single narrowing turns a silent runtime miss into a compile-time warning you can’t miss. It costs you nothing every caller already passes a GameObject metatype anyway and it buys you the diagnostic the wide signature was throwing away. The general principle outlives this one bug: <strong>the wider you type a metatype parameter, the more the compiler has to take on faith.</strong> Reach for the narrowest type the call site can satisfy, and you turn the type checker back into an ally instead of a bystander.</p><h3>Level Up: When Are the Parentheses Actually Correct?</h3><p>(any P).Type isn&#39;t cursed it&#39;s just rarely what you want in a membership check. It&#39;s the right tool when you genuinely mean &quot;the metatype of the existential box itself,&quot; which mostly shows up in deeper metaprogramming corners, not in everyday loop code. In a day-to-day is / as? / as! check against concrete conformers, you essentially never want it.</p><p>And one reassuring note to keep this in perspective: this whole trap <strong>only exists when </strong><strong>.Type is involved.</strong> In ordinary type positions a property type, a function parameter, a return type there&#39;s no ambiguity to trip over:</p><pre>let mesh: any Renderable = StaticMesh()                      // ✅ no .Type, no trap<br>func submit(_ r: any Renderable) { r.render() }              // ✅ totally fine<br>let world: [any GameObject] = [StaticMesh(), AnimatedMesh()] // ✅ fine</pre><p>The danger zone is exact and narrow: <strong>any + </strong><strong>.Type + an </strong><strong>is/</strong><strong>as?/</strong><strong>as! operand.</strong> Everywhere else, add any with a clear conscience.</p><h3>The One-Sentence Summary</h3><blockquote><em>any P.Type = &quot;the </em><em>.self of any concrete conformer&quot; — what your render filter wants. </em><em>(any P).Type = &quot;the metatype of the existential box itself&quot; — almost never what you want in a check.</em></blockquote><p>Same protocol. One pair of parentheses. Opposite runtime answers.</p><h3>A Practical Migration Checklist</h3><p>The workflow I’d recommend whenever you turn on <strong>ExistentialAny</strong> on a codebase that does any runtime type checking:</p><ol><li><strong>Search before you sweep.</strong> Grep for .Type alongside is, as?, and as!. These are your high-risk sites — flag them before any automated fix-it goes near them.</li><li><strong>Review every parenthesised </strong><strong>(any ...).Type.</strong> If it&#39;s the right-hand side of an is/as?/as!, it is almost certainly wrong. Strip the parentheses to any ....Type.</li><li><strong>Trust the successful build less than usual.</strong> With a wide, erased operand this bug type-checks in silence, so a clean build is not the reassurance it normally is.</li><li><strong>Narrow your metatype parameters.</strong> Where a function takes Any.Type, ask whether it could take a protocol metatype like GameObject.Type instead. The tighter type often gives the compiler enough to flag the broken form as &#39;is&#39; test is always false — turning a runtime miss into a build-time warning for free.</li><li><strong>Lean on behavioral tests.</strong> A test that feeds a <em>concrete</em> type into the check and asserts the boolean is the backstop for everything the compiler still can’t see. If you don’t have one for a given check, this is the moment to write it.</li></ol><h3>Summary</h3><p>The migration question started as “should I add any here?&quot; and the actionable answer is: yes but when that any sits next to a .Type in an is/as?/as!, never wrap it in parentheses. any P.Type matches the .self of your real conformers; (any P).Typematches only the existential box itself. They look like twins, they both compile, and exactly one of them keeps your render phase drawing anything at all.</p><p>That’s the kind of bug you only get bitten by once provided you have the test that bites first.</p><h3>Code example</h3><p>Added small code example so you could check it within your browser</p><p><a href="https://swiftfiddle.com/dbgeqqyh6bgadb7mlavzfgcnby">Swift Online Playground</a></p><h3>Let’s Connect!</h3><p>If this saved you an afternoon of staring at a green build wondering why nothing renders, let’s stay in touch:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://x.com/SergeyPekar">@SergeyPekar</a></li></ul><p>I’m a Staff iOS/Android developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance, clean architecture, and business value - let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6b193cc078" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[some vs any in Swift: What's the Difference? Explained Simply (with Examples)!]]></title>
            <link>https://medium.com/@sergey-pekar/some-vs-any-in-swift-whats-the-difference-explained-simply-with-examples-3eb45476ec8d?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb45476ec8d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 10:03:46 GMT</pubDate>
            <atom:updated>2026-06-15T12:11:50.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJF9Vr4wv8LlVdBqZbkvTQ.png" /></figure><p>You probably asking yourself: “who will explain so simple concept in 2026 especially in AI era!?” But as staff iOS engineer interviewing potential candidates I noticed that many of them still don’t understand this concept even in isolation from the SwiftUI where construction like ‘var body: some View’ met in literally every view you create.</p><p>So let’s dive in.</p><p>Imagine you order a beer. There are two ways the bartender can take an order:</p><p><strong>Way 1</strong>: This is your favorite bar and the bartender is your pal like Moe for the Homer in The Simpsons cartoon. Yes he has Duff, Fudd, Budweiser, whatever. But he knows you for about forever so when you are asking: “Gimme <strong>some</strong> (you already know, right?) beer!” he will give you Duff.</p><p><strong>Way 2</strong>: You are organizing a party today and ask your friend to bring a beer. Everyone has its own taste so you know that everyone will bring it according to its own taste and it will be <strong>any</strong> beer. So it will be beer but you don’t know which one.</p><p>Now let’s move to the actual and more child-friendly examples. I guess you will want to explain this concept to someone like he is 5 or probably he/she will be five and we will obviously want our children learn about alcohol as late as possible ;-)</p><p><strong>Our Cast of Characters</strong></p><p>We’ll use the same tiny protocol and the same two types for the <em>entire</em> article. No surprises, no new classes halfway through.</p><pre>protocol Animal {<br>    func sound() -&gt; String<br>}<br><br>struct Dog: Animal {<br>    func sound() -&gt; String { &quot;Woof&quot; }<br>}<br><br>struct Cat: Animal {<br>    func sound() -&gt; String { &quot;Meow&quot; }<br>}</pre><p>A protocol <strong>Animal</strong>, and two structs that conform: <strong>Dog</strong> and <strong>Cat</strong>. Keep these in mind, they&#39;re all we&#39;ll use.</p><p><strong>some</strong>: &quot;One specific type, I promise&quot;</p><p>When you write <strong>some</strong> Animal, you&#39;re saying:</p><blockquote>“This is <em>one</em> concrete type that conforms to Animal. I&#39;m not telling you <em>which</em> one in the signature, but it&#39;s locked to a single type.&quot;</blockquote><pre>func makeDog() -&gt; some Animal {<br>    Dog()<br>}</pre><p>This function returns <strong>some</strong> Animal. The caller doesn&#39;t see the word Dog, but the compiler knows, with certainty, that <strong><em>every</em></strong><em> </em>call returns a Dog. The type is fixed. It just happens to be hidden behind the protocol name.</p><p>Here’s the key rule that trips up novices:</p><pre>func makeAnimal(wantsDog: Bool) -&gt; some Animal {<br>    if wantsDog {<br>        return Dog()<br>    } else {<br>        return Cat()   // ❌ Compiler error!<br>    }<br>}</pre><p>This <strong>does not compile</strong>. Why? Because <strong>some</strong> promised <em>one</em> specific type, and you tried to return two different ones (Dogand Cat). The barista said &quot;I&#39;ll commit to one drink,&quot; then tried to hand you a latte <em>or</em> an espresso depending on the day. Promise broken.</p><p><strong>any</strong>: &quot;Could be any of them&quot;</p><p>When you write <strong>any</strong> Animal, you&#39;re saying:</p><blockquote>“This could be <em>any</em> type that conforms to Animal. It might be a Dog, might be a Cat, might change from one moment to the next.&quot;</blockquote><pre>func makeAnimal(wantsDog: Bool) -&gt; any Animal { // This is the main difference <br>    if wantsDog {<br>        return Dog()<br>    } else {<br>        return Cat()   // ✅ Totally fine!<br>    }<br>}</pre><p>This compiles happily. <strong>any</strong> Animal is flexible, it doesn&#39;t care that you returned different types on different branches. That&#39;s exactly what it&#39;s <em>for</em>.</p><p>The Collection Test (this is where it clicks)</p><p>Let’s say you want a list of animals. Same Dog and Cat.</p><p>With <strong>any</strong>, no problem, you can mix types:</p><pre>let zoo: [any Animal] = [Dog(), Cat(), Dog()]<br><br>for animal in zoo {<br>    print(animal.sound())   // Woof, Meow, Woof<br>}</pre><p>A box of mixed animals. Each element just needs to <em>be “some Animal” </em>(it is not keyword and not a joke I just don’t know how to express it in other word in english), and they can differ. This works.</p><p>Now try the same thing with some:</p><pre>let zoo: [some Animal] = [Dog(), Cat()]   // ❌ Error</pre><p>This fails, because <strong>some</strong> demands that <em>every</em> element be the <em>same</em> single type. A Dog and a Cat are two types. The array can&#39;t satisfy &quot;all one type&quot; when you hand it two.</p><p>But this is fine, because all elements are genuinely the same type:</p><pre>let dogs: [some Animal] = [Dog(), Dog(), Dog()]   // ✅ All Dogs</pre><h4>Why Would I Ever Pick some Over any?</h4><p>Fair question. If <strong>any</strong> is so flexible, why not use it everywhere?</p><p>Two reasons, in plain terms:</p><p><strong>1. </strong><strong>some keeps the real type, </strong><strong>any forgets it.</strong></p><p>With <strong>some</strong>, the compiler still knows the exact underlying type behind the scenes, even though <em>you</em> wrote the protocol name. With <strong>any</strong>, that information is genuinely erased, the compiler only knows &quot;it&#39;s <em>some</em> Animal, who knows which.&quot;</p><p>This matters for performance and for certain compiler features, but as a novice, the practical takeaway is: <strong>some is more precise, </strong><strong>any is more flexible.</strong></p><p><strong>2. Reach for </strong><strong>some by default; reach for </strong><strong>any when you truly need mixing.</strong></p><p>A simple rule of thumb:</p><ul><li>Returning or holding <em>one consistent type</em>? → <strong>some</strong></li><li>Need to <em>mix different types</em> (like that [<strong>any</strong> Animal] zoo)? → <strong>any</strong></li></ul><pre>// One consistent type → some<br>func favoriteAnimal() -&gt; some Animal { Dog() }<br><br>// Mixed bag → any<br>let shelter: [any Animal] = [Dog(), Cat(), Cat()]</pre><h4>The One-Sentence Summary</h4><blockquote><strong>some </strong>Animal = &quot;it&#39;s <em>one specific</em> Animal type, hidden but fixed.&quot;<br><strong>any </strong>Animal = &quot;it&#39;s <em>any</em> Animal type, and it&#39;s allowed to vary.&quot;</blockquote><p>Same protocol. Two promises. <strong>some</strong> promises consistency; <strong>any</strong> promises flexibility.</p><p><strong>Level Up 1</strong>: <strong>some</strong> as a Function Parameter</p><p>So far we’ve seen <strong>some</strong> as a <strong><em>return</em></strong> type. It also works as a <strong><em>parameter</em></strong>. And here&#39;s the neat part: as a parameter, <strong>some</strong> Animal is just a friendlier way of writing a generic.</p><p>If you worked with earlier swift versions you probably written generic functions like this:</p><pre>func describe&lt;T: Animal&gt;(_ animal: T) {<br>    print(animal.sound())<br>}<br><br>describe(Dog())   // Woof<br>describe(Cat())   // Meow</pre><p>But with <strong>some</strong> you could do that in slightly more pleasant syntax:</p><pre>func describe(_ animal: some Animal) {<br>    print(animal.sound())<br>}<br><br>describe(Dog())   // Woof<br>describe(Cat())   // Meow</pre><p>Both say “give me one specific type that conforms to Animal.&quot; <strong>some</strong> is just the shorter, cleaner spelling.</p><p><strong>Level Up 2</strong>: Calling a Method on <strong>any</strong> That <em>Returns</em> the Protocol</p><p>Now a subtle one. Let’s give our protocol a method that returns <em>itself</em>.</p><pre>protocol Animal {<br>    func sound() -&gt; String<br>    func baby() -&gt; any Animal      // a Dog&#39;s baby is an Animal too<br>}<br><br>struct Dog: Animal {<br>    func sound() -&gt; String { &quot;Woof&quot; }<br>    func baby() -&gt; any Animal { Dog() }<br>}<br><br>struct Cat: Animal {<br>    func sound() -&gt; String { &quot;Meow&quot; }<br>    func baby() -&gt; any Animal { Cat() }<br>}</pre><p>Watch what happens when we hold an any Animal and ask for its baby:</p><pre>let pet: any Animal = Dog()<br>let pup = pet.baby()       // pup is also `any Animal`<br>print(pup.sound())         // Woof </pre><p>Looks nice right? But with one very important caveat. Nothing prevents the other developer from writing code like this:</p><pre>struct Cow: Animal {<br>    func sound() -&gt; String { &quot;Mo-o-o-o&quot; }<br>    func baby() -&gt; any Animal { Cat() } // You noticed that?<br>}</pre><p>Let’s. confirm the result:</p><pre>let pet: any Animal = Cow()<br>let pup = pet.baby()       // pup is also `any Animal`<br>print(pup.sound())         // Meow</pre><p>You will probably ask: “What is going on? Why this even allowed?”. But this is not a bug. This is actually how the swift designed. W<strong>hen you call a method on an </strong><strong>any value, anything that method hands back is also </strong><strong>any.</strong> The &quot;I forgot the exact type&quot; property is contagious, it flows from the value to whatever it produces. You don&#39;t get a Cow back; you get an any Animal. The compiler has thrown away the fact that it’s a Cow. That loss of information is the &quot;bug feeling.&quot; You handed in a Cowand got back a mystery box.</p><p>The root cause is the protocol itself. We <em>declared</em> baby() to return any Animal, so that&#39;s all anyone can ever get back. We told the compiler to forget. It obeyed.</p><p><strong>The Fix</strong>: Let the Type Carry Itself, with Self</p><p>Instead of promising <strong>any</strong> Animal, promise that baby() returns <strong>the same type as the thing it&#39;s called on</strong>. Swift spells that Self.</p><pre>protocol Animal {<br>    func sound() -&gt; String<br>    func baby() -&gt; Self          // &quot;returns my own type&quot;<br>}<br><br>struct Dog: Animal {<br>    func sound() -&gt; String { &quot;Woof&quot; }<br>    func baby() -&gt; Self { Dog() }<br>}<br><br>struct Cat: Animal {<br>    func sound() -&gt; String { &quot;Meow&quot; }<br>    func baby() -&gt; Self { Cat() }<br>}</pre><p>Self means &quot;whatever concrete type I actually am.&quot; A Dog&#39;s baby() returns a Dog. A Cat&#39;s returns a Cat. The type is preserved instead of erased.</p><p>Now the type <em>survives</em> the call, as long as the compiler knows the concrete type going in:</p><pre>let dog = Dog()<br>let pup = dog.baby()       // pup is Dog — not any Animal!<br>print(pup.sound())         // Woof<br><br>struct Cow: Animal {<br>    func sound() -&gt; String { &quot;Mo-o-o-o&quot; }<br>    func baby() -&gt; any Animal { Cat() } // ❌ Compiler error!<br>}</pre><h3>Summary</h3><p><strong>some</strong> and <strong>any</strong> both let you work with a protocol instead of a concrete type, but they make opposite promises.</p><p><strong>some</strong> Animal means <strong>one specific type, hidden but fixed</strong>. The compiler knows exactly what it is; you just don&#39;t spell it out. Because it&#39;s locked to a single type, you can&#39;t return a Dog on one path and a Cat on another, and you can&#39;t fill an array with mixed types.</p><p><strong>any</strong> Animal means <strong>any conforming type, free to vary</strong>. A Dog today, a Cat tomorrow, both in the same array, no problem. The trade-off is that the concrete type is forgotten, so anything an <strong>any</strong> value produces comes back as <strong>any</strong> too.</p><p>When you need the type back, as? unlocks it, Self lets a protocol preserve it, and passing through a some parameter re-locks a forgotten type at the function boundary.</p><p>The rule of thumb: <strong>reach for </strong><strong>some by default, switch to </strong><strong>any only when you genuinely need to mix types.</strong> When the compiler complains that your return types don&#39;t match, that&#39;s your signal to switch.</p><h3>Let’s Connect!</h3><p>If you found this article helpful, let’s stay in touch:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://twitter.com/sergey_pekar">@sergey_pekar</a></li></ul><p>I’m a Senior iOS developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance and clean architecture and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb45476ec8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to collect performance stats reliably or iOS Performance Measurement with OSSignpost and Metal…]]></title>
            <link>https://medium.com/@sergey-pekar/how-to-collect-performance-stats-reliably-or-ios-performance-measurement-with-ossignpost-and-metal-5a7284e999f5?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a7284e999f5</guid>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[profiling]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 19:34:25 GMT</pubDate>
            <atom:updated>2026-06-15T12:11:20.708Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to collect performance stats reliably or iOS Performance Measurement with OSSignpost and Metal Debugging Tools</h3><p>If you’ve ever built something that pushes <strong>CPU</strong>, <strong>GPU</strong> or both hard: like a real-time particle simulation, a custom image filter, or a <strong>Metal</strong>-powered renderer, you know the pain of trying to figure out where your frame time goes. And what is more Is the CPU spending too long encoding commands? Is the GPU choking on your compute shader? Or is it that awkward gap between the two where nothing useful happens? And on besides all these questions is how to gather this data in a reliable way to make sure the debugger or logging have not took priceless milliseconds.</p><p><strong>Xcode</strong>’s console and regular breakpoints won’t help much here. When your app processes thousands of particles at 60fps, you’d drown in log output before spotting anything useful. As staff software engineer I felt this pain multiple times during my more than a 14 years iOS development career.</p><p>That’s where Apple’s <a href="https://developer.apple.com/documentation/os/logging"><strong>Unified Logging</strong></a> with <a href="https://developer.apple.com/documentation/os/ossignposter"><strong>OSSignposter</strong></a> comes in for the CPU side, and <a href="https://developer.apple.com/documentation/metal/performance_tuning/using_metal_system_trace_in_instruments_to_profile_your_app)%20with%20[Metal%20Debugger](https://developer.apple.com/metal/tools/"><strong>Metal System Trace</strong></a>] covers the <strong>GPU</strong>. Together, they give you a unified timeline of what both processors are doing — and more importantly, when one is waiting on the other.</p><p>In this article, we’ll build a cloud particle simulation that stresses both CPU and GPU, then profile it using these tools together.</p><h3>What We’re Building</h3><p>Our example app <strong>MetalSky</strong> renders a <strong>physically-based</strong> atmospheric sky with clouds using <strong>Metal</strong> <strong>fragment</strong> <strong>shaders</strong>. The <strong>CPU</strong> handles <strong>matrix</strong> <strong>math</strong> and uniform preparation while the <strong>GPU</strong> runs a per-pixel atmospheric scattering simulation with procedural noise for clouds. This setup is perfect for profiling because the workload is split across both processors and any imbalance will show up immediately.</p><p>Here’s the high-level architecture:</p><ol><li><strong>CPU</strong>: Calculate camera matrices, sun direction, prepare uniform buffers</li><li><strong>GPU</strong>: Run fragment shader to compute atmospheric scattering, Rayleigh and Mie phases, and procedural cloud layers</li><li><strong>GPU</strong>: Run a second pass for post-processing with tone mapping and SSAO</li></ol><h4>Core Components</h4><p>Performance measurement relies on two main classes from Apple’s unified logging framework:</p><ol><li><a href="https://developer.apple.com/documentation/os/logger"><strong>Logger</strong></a>: handles structured log messages with categories and subsystems</li><li><a href="https://developer.apple.com/documentation/os/ossignposter"><strong>OSSignposter</strong></a>: marks time intervals that Instruments can visualise</li></ol><p>On the GPU side, Metal provides its own profiling infrastructure through <a href="https://developer.apple.com/documentation/metal/performance_tuning/using_metal_system_trace_in_instruments_to_profile_your_app"><strong>Metal System Trace</strong></a><strong> </strong>in Instruments and the <a href="https://developer.apple.com/videos/play/wwdc2021/10157"><strong>GPU Timeline</strong></a><strong> </strong>in Metal Debugger.</p><p>For deeper understanding, <strong>Apple</strong> offers excellent resources: the <strong>WWDC</strong> sessions:</p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2020/10168"><strong>Explore logging in Swift</strong></a>,</li><li><a href="https://developer.apple.com/videos/play/wwdc2023/10226"><strong>Debug with structured logging</strong></a>,</li><li>and the documentation section <a href="https://developer.apple.com/documentation/os/logging/recording_performance_data"><strong>Recording Performance Data</strong></a>.</li></ul><p>For Metal-specific profiling, check out Gain insights into your <a href="https://developer.apple.com/videos/play/wwdc2020/10605"><strong>Metal app with Xcode 12</strong></a> (I know it is a bit old already but still relevant) and <a href="https://developer.apple.com/videos/play/wwdc2021/10157/"><strong>Discover Metal debugging, profiling, and asset creation tools</strong></a>.</p><h3><strong>Setting Up Performance Logging</strong></h3><p>Every measurement task requires creating instances of <strong>Logger</strong>, <strong>OSSignposter</strong>, and optionally <strong>OSSignpostID</strong> for parallel operations. Let’s set this up in our particle(obviously the size of the app is too large for posting whole code here, so encouraging you to check out it on the GitHub if you are interested):</p><pre>swift<br>import OSLog<br>import Metal<br>import MetalKit<br><br>final class SkyRenderer: NSObject, MTKViewDelegate {<br><br>    // MARK: - Metal Infrastructure<br>    private let device: MTLDevice<br>    private let commandQueue: MTLCommandQueue<br><br>    // Render pipelines<br>    private let skyPipelineState: MTLRenderPipelineState<br>    private let directSkyPipelineState: MTLRenderPipelineState<br>    private let postPipelineState: MTLRenderPipelineState<br><br>    // MARK: - State<br>    private let startTime: CFTimeInterval<br>    private var camera: Camera<br>    private var renderSettings: RenderSettingsSnapshot<br><br>    // MARK: - Performance Logging<br>    private let logger: Logger<br>    private let signposter: OSSignposter<br><br>    init(device: MTLDevice, colorPixelFormat: MTLPixelFormat) throws {<br>        guard let commandQueue = device.makeCommandQueue() else {<br>            throw RendererError.noCommandQueue<br>        }<br><br>        self.device = device<br>        self.commandQueue = commandQueue<br>        self.startTime = CACurrentMediaTime()<br>        self.camera = Camera()<br><br>        // Performance logging setup<br>        logger = Logger(<br>            subsystem: Bundle.main.bundleIdentifier ?? &quot;dev.sergeypekar.MetalSky&quot;,<br>            category: &quot;SkyRenderer&quot;<br>        )<br>        signposter = OSSignposter(logger: logger)<br><br>        // Load shader library and create pipeline states ...<br>        guard let library = device.makeDefaultLibrary() else {<br>            throw RendererError.noLibrary<br>        }<br><br>        // Sky pipeline: atmospheric scattering into offscreen HDR texture<br>        let skyPipelineDesc = MTLRenderPipelineDescriptor()<br>        skyPipelineDesc.vertexFunction = library.makeFunction(name: &quot;skyVertex&quot;)<br>        skyPipelineDesc.fragmentFunction = library.makeFunction(name: &quot;skyFragment&quot;)<br>        skyPipelineDesc.colorAttachments[0].pixelFormat = .rgba16Float<br>        skyPipelineDesc.depthAttachmentPixelFormat = .depth32Float<br>        self.skyPipelineState = try device.makeRenderPipelineState(<br>            descriptor: skyPipelineDesc<br>        )<br><br>        // ... additional pipeline setup omitted for brevity ...<br>    }<br>}</pre><p><em>The </em><strong><em>Logger</em></strong><em> is created with a subsystem matching the app’s bundle identifier and a category identifying the renderer class. The </em><strong><em>OSSignposter</em></strong><em> wraps that logger so every signpost interval automatically inherits the same subsystem and category. This makes filtering easy later in Instruments.</em></p><h4>Measuring the Frame Loop</h4><p>Now let’s instrument the actual frame loop. This is where it gets interesting, we’ll measure each phase of our simulation separately so we can see exactly where time is spent:</p><pre>func draw(in view: MTKView) {<br>    let frameState = signposter.beginInterval(&quot;Frame&quot;, &quot;Full frame&quot;)<br>    defer { signposter.endInterval(&quot;Frame&quot;, frameState) }<br><br>    // Phase 1: Prepare uniforms (CPU computation)<br>    let uniformState = signposter.beginInterval(&quot;Prepare Uniforms&quot;,<br>                                                 &quot;CPU computation&quot;)<br><br>    let elapsed = Float(CACurrentMediaTime() - startTime)<br>                  * renderSettings.timeScale<br>    let aspect = viewportSize.x / viewportSize.y<br>    let fovY = renderSettings.fovYDegrees * (.pi / 180.0)<br><br>    camera.pitch = renderSettings.cameraPitchRadians<br>    let projection = perspectiveMatrix(fovY: fovY, aspect: aspect,<br>                                       near: 0.1, far: 100.0)<br>    let viewMatrix = camera.viewMatrix<br>    let sunDir = sunDirection(<br>        azimuth: renderSettings.sunAzimuthRadians,<br>        elevation: renderSettings.sunElevationRadians<br>    )<br><br>    var skyUniforms = SkyUniforms(<br>        invProjection: projection.inverse,<br>        invView: viewMatrix.inverse,<br>        time: elapsed,<br>        cirrus: renderSettings.cirrus,<br>        cumulus: renderSettings.cumulus,<br>        sunDirection: sunDir,<br>        resolution: viewportSize<br>    )<br><br>    signposter.endInterval(&quot;Prepare Uniforms&quot;, uniformState)<br><br>    // Phase 2: Encode render commands<br>    let encodeState = signposter.beginInterval(&quot;Encode Commands&quot;,<br>                                                &quot;Metal encoding&quot;)<br><br>    guard let commandBuffer = commandQueue.makeCommandBuffer(),<br>          let drawable = view.currentDrawable,<br>          let screenPassDesc = view.currentRenderPassDescriptor else { return }<br><br>    let encoder = commandBuffer.makeRenderCommandEncoder(<br>        descriptor: screenPassDesc<br>    )!<br>    encoder.setRenderPipelineState(directSkyPipelineState)<br>    encoder.setFragmentBytes(&amp;skyUniforms,<br>                              length: MemoryLayout&lt;SkyUniforms&gt;.stride,<br>                              index: 0)<br>    encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)<br>    encoder.endEncoding()<br><br>    signposter.endInterval(&quot;Encode Commands&quot;, encodeState)<br><br>    // Phase 3: Present and commit<br>    let presentState = signposter.beginInterval(&quot;Present&quot;, &quot;GPU submission&quot;)<br><br>    commandBuffer.present(drawable)<br>    commandBuffer.commit()<br><br>    signposter.endInterval(&quot;Present&quot;, presentState)<br>}</pre><p>Notice how we measure three distinct phases. “<strong>Prepare Uniforms</strong>” covers the CPU-side matrix math and sun direction calculation. “<strong>Encode Commands</strong>” covers <strong>Metal</strong> render pass encoding. “<strong>Present</strong>” covers drawable presentation and command buffer submission. Each one will appear as a separate interval in Instruments making it immediately obvious which phase dominates your frame time.</p><h4><strong>The Uniform Structs</strong></h4><p>Before the GPU can render anything the CPU must prepare uniform data. MetalSky uses two structs that bridge Swift and Metal. Their memory layout must match exactly between the two languages:</p><pre>struct SkyUniforms {<br>    var invProjection: simd_float4x4<br>    var invView: simd_float4x4<br>    var time: Float<br>    var cirrus: Float<br>    var cumulus: Float<br>    var padding: Float = 0         // align to 8-byte boundary<br>    var sunDirection: SIMD3&lt;Float&gt;<br>    var sunPadding: Float = 0<br>    var resolution: SIMD2&lt;Float&gt;<br>    var padding2: SIMD2&lt;Float&gt; = .zero  // pad to 16-byte struct alignment<br>}</pre><p><em>These padding fields matter. Metal expects struct members to be aligned to specific boundaries. A misaligned field will silently read garbage data on the GPU which makes for confusing debugging sessions. Always verify your Swift struct layout matches the Metal shader definition.</em></p><h4>The Sky Fragment Shader</h4><p>Here is the Metal shader that runs on the GPU. It computes per-pixel atmospheric scattering with Rayleigh and Mie phases plus procedural cloud layers using fractional Brownian motion noise:</p><pre>fragment float4 skyFragment(VertexOut in [[stage_in]],<br>                            constant SkyUniforms &amp;uniforms [[buffer(0)]]) {<br>    // Reconstruct view direction from screen coordinates<br>    float2 ndc = in.uv * 2.0 - 1.0;<br>    float4 clipPos = float4(ndc.x, ndc.y, 1.0, 1.0);<br>    float4 viewPos = uniforms.invProjection * clipPos;<br>    viewPos.xyz /= viewPos.w;<br>    viewPos.w = 0.0;<br>    float3 pos = normalize((uniforms.invView * viewPos).xyz);<br><br>    float3 fsun = normalize(uniforms.sunDirection);<br><br>    // Atmospheric scattering constants<br>    constexpr float Br = 0.0025;   // Rayleigh coefficient<br>    constexpr float Bm = 0.0003;   // Mie coefficient<br>    constexpr float g  = 0.98;     // Mie phase asymmetry<br>    float3 nitrogen = float3(0.650, 0.570, 0.475);<br><br>    float3 Kr = Br / pow(nitrogen, float3(4.0));<br>    float3 Km = Bm / pow(nitrogen, float3(0.84));<br><br>    float mu = dot(pos, fsun);<br>    float rayleigh = 3.0 / (8.0 * 3.14159) * (1.0 + mu * mu);<br>    float mie = (Kr.x + Km.x * (1.0 - g * g) / (2.0 + g * g) /<br>                pow(1.0 + g * g - 2.0 * g * mu, 1.5)) / (Br + Bm);<br><br>    // Extinction and final color ...<br>    float3 color = rayleigh * mie * extinction;<br><br>    // Cirrus clouds using fractional Brownian motion<br>    float density = smoothstep(1.0 - uniforms.cirrus, 1.0,<br>        fbm(pos.xyz / pos.y * 2.0 + uniforms.time * 0.05));<br>    color = mix(color, extinction * 4.0, density * 0.3);<br><br>    // Cumulus clouds with multiple depth layers<br>    for (int i = 0; i &lt; 5; i++) {<br>        float cDensity = smoothstep(1.0 - uniforms.cumulus, 1.0,<br>            fbm((0.7 + float(i) * 0.01) * pos.xyz / pos.y +<br>                uniforms.time * 0.3));<br>        color = mix(color, extinction * cDensity * 5.0,<br>                    min(cDensity, 1.0) * 0.4);<br>    }<br><br>    return float4(color, 1.0);<br>}</pre><p>The GPU handles the heavy per-pixel math while the CPU handles higher-level concerns like camera transformation and settings. This split is where profiling becomes essential. You need to know if one side is starving the other.</p><h4>The Noise Functions</h4><p>The cloud generation in MetalSky relies on a <strong>fbm</strong> (fractional Brownian motion) function that sums five octaves of 3D noise:</p><pre>static float fbm(float3 p) {<br>    float3x3 m = float3x3(<br>        float3( 0.0,  1.60,  1.20),<br>        float3(-1.60,  0.72, -0.96),<br>        float3(-1.20, -0.96,  1.28)<br>    );<br><br>    float f = 0.0;<br>    f += noise(p) / 2.0;   p = m * p * 1.1;<br>    f += noise(p) / 4.0;   p = m * p * 1.2;<br>    f += noise(p) / 6.0;   p = m * p * 1.3;<br>    f += noise(p) / 12.0;  p = m * p * 1.4;<br>    f += noise(p) / 24.0;<br>    return f;<br>}</pre><p>Each octave applies a rotation matrix before sampling to reduce directional artifacts. This is called six times per pixel when cumulus clouds are visible (once for cirrus and five times for the cumulus layers). That makes <strong>fbm</strong> the most performance-critical function in the entire shader and a prime target for profiling.</p><h3>Environment Configuration</h3><p>Before profiling verify your scheme’s environment variables:</p><ol><li><strong>OS_ACTIVITY_MODE - </strong>must <strong>NOT</strong> be set to <strong>disable</strong> (many developers disable it to suppress autolayout and other iOS internal warnings)</li><li><strong>SIGNPOSTS - </strong>should be defined (any value) to enable signpost recording</li></ol><p>You can configure these in Xcode under <strong>Product &gt; Scheme &gt; Edit Scheme &gt; Run &gt; Arguments &gt; Environment Variables </strong>(see the screenshot below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CwkX_c8takHwQYi9yG3isg.png" /><figcaption>Correct environment variables setup</figcaption></figure><p>Without the <strong>SIGNPOSTS </strong>variable the logger disables itself to eliminate measurement overhead during normal execution.</p><p>And just be fore we started I want to answer quite an often and reasonable question: “Why not just use <strong>print</strong> statements?”.</p><h4>OSSignpost vs Print Logging: Why It Matters for Metal Apps</h4><p>You might wonder why not just use <strong>print()</strong> with timestamps. The difference becomes critical in <strong>Metal</strong> apps where you are trying to correlate <strong>CPU</strong> and <strong>GPU</strong> work.</p><h4>The Problem with Print Statements</h4><pre>func draw(in view: MTKView) {<br>    let start = CFAbsoluteTimeGetCurrent()<br>    print(&quot;[\(start)] Frame started&quot;)<br><br>    // ... prepare uniforms, encode commands ...<br><br>    let encodeEnd = CFAbsoluteTimeGetCurrent()<br>    print(&quot;[\(encodeEnd)] Encoding done: \(encodeEnd - start)s&quot;)<br><br>    commandBuffer.present(drawable)<br>    commandBuffer.commit()<br><br>    let commitEnd = CFAbsoluteTimeGetCurrent()<br>    print(&quot;[\(commitEnd)] Committed: \(commitEnd - encodeEnd)s&quot;)<br>}</pre><p>This approach has several issues:</p><ul><li><strong>I/O overhead:</strong> Each `print()` blocks the thread while writing to stdout. In a 60fps render loop that is 180+ log lines per second adding latency to your frame.</li><li><strong>No GPU correlation:</strong> Print timestamps live in a different world from Metal’s GPU timeline. You cannot align them to see what the GPU was doing when the CPU was encoding.</li><li><strong>No visualisation:</strong> You are left parsing text output to spot patterns.</li><li><strong>Always active:</strong> Logging statements remain active unless stripped manually and they affect release builds.</li></ul><h4>The OSSignpost Advantage</h4><pre>func draw(in view: MTKView) {<br>    let frameState = signposter.beginInterval(&quot;Frame&quot;, &quot;Full frame&quot;)<br>    defer { signposter.endInterval(&quot;Frame&quot;, frameState) }<br><br>    // ... phases measured as shown above ...<br>}</pre><p>OSSignpost solves these problems:</p><ul><li><strong>Minimal overhead:</strong> Signposts are designed for high-frequency capture with negligible performance impact.</li><li><strong>Precise timestamps:</strong> The system captures timing at the kernel level not in your code.</li><li><strong>Visual timeline:</strong> Instruments renders interactive timelines alongside Metal System Trace tracks.</li><li><strong>Zero cost when disabled:</strong> Without the `SIGNPOSTS` environment variable logging compiles to no-ops.</li></ul><h3>Profiling with Instruments: CPU + GPU Together</h3><p>This is where things come together. Running both <strong>os_signpost</strong> and <strong>Metal System Trace</strong> instruments simultaneously gives you a unified timeline showing exactly how CPU and GPU work overlap.</p><h4>Building for Profiling</h4><p>Prepare your app using one of these methods:</p><ul><li>Press <strong>Cmd+Shift+I</strong></li><li>Long-press the Build (keeping pressed Shift key in Xcode 26) button and select <strong>Build for Profiling</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*gpGTDA1DqiNf2XEpFIohPA.png" /></figure><h4>Configuring the Instruments Session</h4><p>After a successful build Xcode opens the Instruments template picker:</p><ol><li>Select the “<strong>Blank”</strong> template</li><li>Click the “<strong>+”</strong> button in the top-left corner</li><li>Add the “<strong>os_signpost”</strong> instrument to capture your custom signpost intervals</li><li>Add the “<strong>GPU”</strong> instrument to capture GPU work, encoder timelines, and shader execution</li><li>Press “<strong>Record”</strong> and interact with your app</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glyfgHWweNpl-ePWNfqSdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7Wb82HS5LZoLtsNmVcOKQ.png" /></figure><p>After waiting for a couple of seconds, minutes, hours, depending on your particular issue, you will see something like that (screenshot below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPB_IetLX1Vcx0Gj5pb94w.png" /></figure><p>Not very informative but you can already see some patterns</p><p>OK let’s dive into signposts first</p><p><strong>os_signpost</strong> track shows your custom intervals (you shouldd press arrow button near os_signpost instrument, scroll down to your bundle ID in my case it is dev.sergeypekar.MetalSky and also press the arrow button). “Prepare Uniforms”, “Encode Commands”, and “Present”. You can see how long each CPU phase takes and spot any that spike unexpectedly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmZ3KLGvEybqk6tUSUclJA.png" /></figure><p>You probably noticed SkyRenderer section below the bundle ID, this is OSLog category which you assigned by creating OSLog instance that is used as the parent object for OSSignposter. You could have multiple OSLog instances and they all will be shown on the timeline so you could track subsystem lifecycles and many other interesting events.</p><p>Both instruments generate a lot of data. Filter the os_signpost output by subsystem (the bundle identifier you passed to `Logger`) to focus on your renderer code. In Metal System Trace focus on the fragment shader timeline since that is where the atmospheric scattering and cloud generation runs.</p><h3>Analysis</h3><p>Select a portion of the timeline to view statistics for that specific time window. This is very useful for comparing performance across different scenarios. For example try different cirrus and cumulus density values or switch between the direct rendering path and the two-pass post-processing path. Instruments will show you min, max, average, and standard deviation for each signpost interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XeW5oEragVDLk8NE1chGg.png" /></figure><p>For example from the screenshot above we can definitely say that “Prepare Uniforms” stem take a fraction of all the frame time and probably is not worth our attention while “Metal Encoding” takes almost all the frame time and we should examine it a bit deeper.</p><p>At the time of writing this article there is no standard way to create hierarchy of events. In the graph they will be displayed as separate graphs even though one could be nested inside another. So you would need to keep track of their relationship on your own.</p><h4>Metal Debugger: Going Deeper on the GPU Side</h4><p>While Instruments gives you the runtime timeline Xcode’s Metal Debugger lets you freeze a single frame and inspect it in detail. This is where you analyse what is happening inside your fragment shader.</p><p>With your app running from Xcode click the “M button” in the debug bar to capture a <strong>GPU</strong> frame. This snapshots all <strong>Metal</strong> commands, resources, and shader executions for one frame.</p><p>Let’s move straight to the “<strong>Performance</strong>” section</p><p>The GPU <strong>Timeline</strong> in <strong>Metal Debugger </strong>combines what you would see in Metal System Trace with per-encoder GPU counter data. For MetalSky you will see:</p><ul><li>The render encoder running `skyFragment` for the atmospheric sky</li><li>If post-processing is enabled a second render encoder running `postFragment` for tone mapping and SSAO</li><li>Any gaps between them where the GPU is idle</li></ul><p>If you notice non-overlapping GPU work in the timeline that is over-serialisation and a sign that your command buffer structure needs attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08z7c1yu-PYx60RNyTdU5Q.png" /></figure><h4>Shader Profiler</h4><p>Navigate to <strong>View Frame By Pipeline State</strong> and select your sky pipeline. The shader profiler shows per-line execution cost of your Metal shader. This tells you exactly which lines consume the most GPU time.</p><p>For MetalSky you will likely discover that the “fbm” noise calls dominate the fragment shader cost. The cumulus cloud loop calls “fbm” five times and each `fbm` call runs five octaves of noise. That is 25 noise evaluations per pixel just for cumulus clouds. The shader profiler will show this clearly. That is actionable information. You could reduce the octave count or precompute a noise texture on the CPU and sample it in the shader instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfTkIV4g83karWBZb9jYjQ.png" /><figcaption>The most expensive part of the shader</figcaption></figure><p>On A11 and newer chips you will also see the ALU vs. memory cost breakdown per line. The atmospheric scattering math (Rayleigh and Mie phase calculations) should show up as ALU-heavy while the matrix multiplies for ray reconstruction may show more balanced cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlJf86qeaXLRE8ELqiM-Iw.png" /><figcaption>ALU cost of operation</figcaption></figure><h3>Putting It All Together</h3><p>Here is the workflow I would recommend for profiling a Metal app like MetalSky:</p><ol><li><strong>Start with Instruments</strong>. Run os_signpost + Metal System Trace together to get the big picture. Identify whether you are CPU-bound or GPU-bound.</li><li><strong>Zoom into the GPU</strong>. If the fragment shader execution looks expensive capture a frame with Metal Debugger. Use the shader profiler to find hot lines in your sky fragment shader. The `fbm` noise function and the cumulus cloud loop are the usual suspects.</li><li><strong>Correlate back to CPU</strong>. If your signpost data shows long “Prepare Uniforms” intervals check whether the matrix inversions or sun direction calculations are more expensive than expected. In MetalSky the CPU work is lightweight but in a more complex renderer with many objects this phase can grow.</li><li><strong>Iterate.</strong> After making changes run the same Instruments session again and compare. Select identical time ranges in the timeline to get directly comparable statistics.</li></ol><h3>Summary</h3><p>When your app pushes both CPU and GPU no single tool tells the whole story. OSSignpost captures your CPU-side logic with kernel-level precision. Metal System Trace reveals what the GPU is actually doing. Metal Debugger lets you drill into individual shaders and draw calls.</p><p>Together they transform the question from “why is my frame rate low?” into “the CPU spends 0.2ms preparing uniforms, the fragment shader spends 6ms on atmospheric scattering and cloud noise, and the cumulus fbm loop accounts for 4ms of that.”</p><p>That is the kind of answer you can act on.</p><h3>Let’s Connect!</h3><p>If you found this article helpful, let’s stay in touch:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://twitter.com/sergey_pekar">@sergey_pekar</a></li></ul><p>I’m a Staff iOS/Android developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance and clean architecture and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a7284e999f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fix annoying Xcode 26 not building SwiftUI previews (error: cannot execute tool ‘metal’ due…]]></title>
            <link>https://medium.com/@sergey-pekar/how-to-fix-annoying-xcode-26-not-building-swiftui-previews-error-cannot-execute-tool-metal-due-49564e20357c?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/49564e20357c</guid>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 16:00:53 GMT</pubDate>
            <atom:updated>2026-06-15T12:12:45.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to fix annoying Xcode 26 not building SwiftUI previews (error: cannot execute tool ‘metal’ due to missing Metal Toolchain; use: xcodebuild -downloadComponent MetalToolchain)</h3><p>I guess you already installed Xcode 26, and if you are using Metal in your application, probably faced this annoying error when installed metal toolchain, built your app. But when you tried to preview any SwiftUI view you saw this: “error: cannot execute tool ‘metal’ due to missing Metal Toolchain; use: xcodebuild -downloadComponent MetalToolchain”. Yeah, pretty annoying, right?</p><p>This is a bug related to the Metal toolchain, which is unbundled from Xcode and should be downloaded separately starting from Xcode 26. Unfortunately, this bug appeared in beta and migrated to the release version of Xcode.</p><p>The core reason of this bug is that Xcode saves the downloaded Metal toolchain to the incorrect location. So what we should do is to fix that.</p><p>First of all, if you already installed the metal toolchain, delete it and start over.</p><p>First step: We need to run the following command in the terminal:</p><pre>xcodebuild -downloadComponent metalToolchain</pre><p>This is required to see the exact location where this toolchain has been downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*slXKSlVoRh7oyGkLDw6SQA.png" /><figcaption>Downloading Metal toolchain</figcaption></figure><p>As you can see on the screenshot above, in my case the download path is: /System/Library/AssetsV2/com_apple_MobileAsset_MetalToolchain/4ab058bc1c53034b8c0a9baca6fba2d2b78bb965.asset/AssetData/Restore/</p><p>Then you need to copy this path and run the following commands to open the directory:</p><pre>cd &lt;your copied path&gt;<br>open .</pre><p>Alternatively, you can open the Finder and press Command-Shift-G and navigate to the directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYJyAVUhhdDgBZA-1fU0Ew.png" /><figcaption>Navigating to the metal toolchain download directory through finder</figcaption></figure><p>After you open the directory, you should find a file with a.dmg extension and open it with the DiscImageMounter application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpK9y9l8LHoTBOm908qh_Q.png" /><figcaption>Mounting metal toolchain disk image</figcaption></figure><p>After the successful mount, you should see the following window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bZJ5nZ43hSEQhzY_Zfgfw.png" /><figcaption>Contents of the .dmg disk image</figcaption></figure><p>We are interested in Metal.xctoolchain file. Copy it here: /Applications/Xcode.app/Contents/Developer/Toolchains</p><p>To access the contents folder of the Xcode app, you should right-click on the Xcode app and press “Show Package Contents” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*bK1NT3qMxG-eqL41I1GlJQ.png" /><figcaption>Accessing Contents folder inside Xcode app</figcaption></figure><p>After you restart Xcode, you should see that Toolchains menu section appered under the Xcode section. So, go to this menu section and select Metal (See the screenshot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7Lu1BaTTn2E-h6dhJokjQ.png" /><figcaption>Selecting Metal toolchain</figcaption></figure><p>Now all the previews should be compiled successfully. So happy coding!</p><p>Btw, if you’re still facing infinite loop on Preview compilation, you can try to go to the editor, canvas, and check the “Use legacy preview execution” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWxTcAHSi6mr3GpLCVrXnw.png" /></figure><h3>Let’s Connect!</h3><p>If you found this article helpful, let’s stay in touch:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://twitter.com/sergey_pekar">@sergey_pekar</a></li></ul><p>I’m a Staff iOS/Android developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance and clean architecture and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49564e20357c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to remove files from the git repo]]></title>
            <link>https://medium.com/@sergey-pekar/how-to-remove-files-from-the-git-repo-35cefe96be05?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/35cefe96be05</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-history]]></category>
            <category><![CDATA[source-control]]></category>
            <category><![CDATA[clean-git-history]]></category>
            <category><![CDATA[git-clean]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 07:45:57 GMT</pubDate>
            <atom:updated>2026-06-15T12:13:33.017Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever faced the situation when you committed some files to the Git repo that should not be there? For example, some binaries, private keys or whatever?</p><p>Pretty bad situation, right? This can lead to several consequences, from wasting space in your Git repository to even worse — you submitted some private information that can be used by someone else. In my situation, private data was not the case because I was only a developer on a private repository. But one time I exceeded the size limit of my repo and decided to move to GitHub from the bitbucket. Accidentally I noticed that there is a 100MB size limit (yep I know there is LFS for such stuff but when I started the project about 10 years go I was unaware of this), so my repo just could not be imported to GitHub. And moreover, it is some very old file which I cannot find in my git history. I started to look for the way to remove the large old file from the Git repo.</p><p>So what to do in such a situation? Don’t worry, I got you covered! Actually, there are several utils to remove commited files from the Git repository.</p><p>One of them is <a href="https://github.com/newren/git-filter-repo">git-filter-repo</a>. This is a Python tool which could be found <a href="https://github.com/newren/git-filter-repo">here</a>. And the second one is <a href="https://rtyley.github.io/bfg-repo-cleaner/">BFG</a>. This is a Java utility that can be found <a href="https://github.com/rtyley/bfg-repo-cleaner">here</a>.</p><p>My personal preference is BFG just because I have the Java installed, and I can work with this tool simply by downloading and running the JAR.</p><p>You can download BFG from here or compile it from sources on the Github. As I mentioned earlier, it’s a simple Java library, and could be run by running the Java command with -jar parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKuPZWCR4DtWNo3G7EHS-w.png" /><figcaption>Running bfg</figcaption></figure><p>Okay first, if you pushed some private info like private keys, tokens, and so on, it’s better to revoke them if you can.It is a common practise to revoke any private data exposed to the Internet. Thus, you will be sure that nobody will use it.</p><p>Then you can perform the actual cleanup. First, you need to copy your repository with all your branches. This could be done by running git clone with--mirror flag. This flag is required because we need the full copy of the repo with all branches and tags (If your repository is pretty old, it can take a significant amount of time and storage since it’s cloning the full repository with full history.). This command will create a folder named as your repository.git, then should go to this folder.</p><pre>git clone --mirror git@github.com:your/repo.git<br>cd repo.git</pre><p>This utility is not limited to specific files. You can delete folders, convert large files to Git LFS, or delete folders or even specify some text patterns that you want to alter. I really encourage you to check the manual for the BFG utility because it provides the vast amount of features for cleaning up your Git repository.</p><p>In my case, I want to delete everything that is in the folder AndroidSigning. So my command looked like this. (I suggest you make a copy of your repository in some other folder to make sure you won’t remove anything important. Just make sure that you have a backup.)</p><pre>java -jar bfg-1.15.0.jar --delete-folders AndroidSigning</pre><p>Output depends on the task you try to run, but it should be something similar to what you see on the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6el7ap9OT3wnRdMpLwkqQ.png" /></figure><p>Although BFG recommends running it together, i prefer to run them separately. Thus you will see which exact command produced any error.</p><p>Let’s do them. Btw, I recommend you to check out the logs in the BFG command because you can lose some valuable information. So do this before you run the following commands.</p><pre>git reflog expire --expire=now --all<br>git gc --prune=now --aggressive</pre><p>Assume you’ve checked the loads and everything is OK. So now let’s push changes to the Git. As you see I’m using — force flag. This is flag is required. Otherwise, Git will simply reject your changes.</p><pre>git push --force</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDhN0e_bn2oa9Wy_AqZUIw.png" /><figcaption>The result of running git push — force</figcaption></figure><p>Of course, we can’t blindly trust this command. Let’s perform `git log` to make sure files and folders and whatever is gone indeed.</p><pre>git log -p -- AndroidSigning</pre><p>As you can see on screen, it shoots the folder is completely gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjWxeOhuwX0MHmYuosO8sg.png" /><figcaption>The result of running git log for the AndroidSigning folder after we deleted it.</figcaption></figure><p>For comparison, I also showing the screenshot with the git log command when the folder was still present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoSYF5mrdPk0UWwEKj9XUA.png" /><figcaption>How the log looked like before we deleted the AndroidSigning directory.</figcaption></figure><p>After that, all team members should reclone this repository because local data on their computers is still preserved and will cause conflicts when someone will try to push changes using git repo with old history. You need to reclone the project to make sure there is no any data in the repository. Also, all these commands rewrite your commit history and commit hashes, so keep that in mind (this will be the exact reason of any conflict, history is overwritten).</p><p>Sometimes the org won’t delete your files and mark the content as dirty as you can see in the log.</p><p>In this case, you should make a commit that manually removes all these files and performs the steps described above.</p><p>Happy Cleanup!</p><h3>Let’s Connect!</h3><p>If you found this article helpful, let’s stay in touch:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://twitter.com/sergey_pekar">@sergey_pekar</a></li></ul><p>I’m a Staff iOS/Android developer with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance and clean architecture and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35cefe96be05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xcode Localization: approaches to have different localisations for different targets.]]></title>
            <link>https://medium.com/@sergey-pekar/xcode-localization-approaches-to-have-different-localisations-for-different-targets-9cbfaef4aa4d?source=rss-d0b53589ed5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbfaef4aa4d</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[localisation-testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[localisation]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Sergey Pekar]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 19:28:53 GMT</pubDate>
            <atom:updated>2026-06-15T12:12:29.979Z</atom:updated>
            <content:encoded><![CDATA[<p>When the iOS application becomes successful and grow enough on local market it becomes obvious the the following step to grow app further is the translation of the app strings to the local languages. This is not only makes the app more accessible for the users abroad but also is good for the ASO and installs conversions.</p><p>Usually the localisation is not the case. It is pretty easy to translate the app and put everything to the <strong>String Catalog. </strong>(I assume you have already updated your app to at least iOS 15 😉 and you migrated from the Localizable.string, however the process is similar). But the actual challenge is to handle multiple translations in process along with heavy feature development. In most cases you won’t have incomplete or untested translation accidentally appear in new version of the app. And this is the situation where multiple targets come in place (if you don’t already have them).</p><p>Let’s create simple app and see how we can manage different translations with multiple targets of the application.</p><p>I created a simple app called LocalizationExample. Nothing special just empty SwiftUI project.</p><p>Let’s create siple extension for String for easier handling of localized resources. In our case localizable key will be the string itself but you can use any system that is better for you.</p><pre>extension String {<br>    var localized: String {<br>        NSLocalizedString(self, comment: &quot;&quot;)<br>    }<br>}</pre><p>Here we go. Nothing special just calling NSLocalizedString inside.</p><p>Now let’s use it in our code:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>            Image(systemName: &quot;globe&quot;)<br>                .imageScale(.large)<br>                .foregroundStyle(.tint)<br>            <br>            Text(&quot;Hello localized string&quot;.localized) // use localized string<br>        }<br>        .padding()<br>    }<br>}</pre><p>Also let’s create String catalog and add this string as a key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*tzzLGxeXC4dhkSocqpmL5g.png" /><figcaption>This is ho String catalog look like</figcaption></figure><p>Done. You can also add Spanish localisation (or any other translation) to the String catalog. It won’t appear in the app unless you translate at least one string.</p><p>Also let’s create a staging target. All you need to do is to click on the target and press <strong>Command+D</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*BiYYzF3i2bXapHNLm1y2sg.png" /><figcaption>Staging target for testing</figcaption></figure><p>Then go to General tab and change the bundle identifier to something different like (com.example.LocalizationExampleStaging) this is required for the system to distinguish main target and staging target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDYQvMTwcsbAkwrz1c2hUg.png" /><figcaption>Update bundle identifier</figcaption></figure><p>Here we go, now we have everything needed for testing approaches.</p><h4>First approach: Multiple String catalogs</h4><p>As you just read we will simply create a new string catalog and add missing localisation to it. Let’s name it <strong>Localisation Staging</strong> and add spanish localisation for our string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*lHncpMOoA9i_SH_yzI6XVg.png" /><figcaption>Additional String catalog</figcaption></figure><p>Now let’s create simple extension for our Bundle which helps us to understand which target we are using at runtime.</p><pre>import Foundation</pre><pre>extension Bundle {<br>    var isStaging: Bool {<br>        Bundle.main.bundleIdentifier?.contains(&quot;Staging&quot;) ?? false<br>    }<br>}</pre><p>Now let’s modify our String extension to use this property and use either default String catalog or Stagaing version. For that purpose we are using tableName parameter of NSLocalizedString function.</p><pre>import Foundation</pre><pre>extension String {<br>    <br>    var localized: String {<br>        NSLocalizedString(<br>            self,<br>            tableName: Bundle.main.isStaging ? &quot;Localizable Staging&quot; : nil,<br>            comment: &quot;&quot;<br>        )<br>    }<br>}</pre><p>Now let’s select our new target and update it’s schema to use other language. This is required to preview the localisation on SwiftUI preview or iOS simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*n4yGaGCRGytzcgoPvYB3MA.png" /><figcaption>Select new target</figcaption></figure><p>Fot this you should go to Product -&gt; Scheme -&gt; Edit Scheme..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RWX3kWmO-WVuUlS7dm3ig.png" /><figcaption>Editing sheme</figcaption></figure><p>Then select Run -&gt; Options, scroll down and select desired language under “App Language” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeijY2KVI5umnSTQyc2e9g.png" /><figcaption>Selecting app language to preview translation in iOS simulator or SwiftUI preview</figcaption></figure><p>Now let’s open the preview. Whoa la we are displaying translated text that exits only in Staging taget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Tz9LJwh6Phsbzw1hgIXgew.png" /></figure><h4>Second approach: Same default String catalogs with different target membership</h4><p>Let’s start over from the simplest extension for the String.</p><pre>extension String {<br>    var localized: String {<br>        NSLocalizedString(self, comment: &quot;&quot;)<br>    }<br>}</pre><p>Now let’s repeat the steps with creating Strings catalog and Staging target.</p><p>Now let’s create “Resources” Folder and “Resources Staging” folder and copy our Localizable.xcstrings into both folders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*c3QHMVDolDo_22xQcFFsaA.png" /></figure><p>Now let’s add Spanish translation to only <strong>Localizable.xcstrings</strong> under “Resources Staging” folder. So far so good. But now there is the only problem: system won’t be able to distinguish these String catalogs. So we should select each <strong>Localizable.xcstrings</strong> under “Resources Staging” and go to the file inspector. And update it’s target membership to be included only in our Staging target. Also make sure our main <strong>Localizable.xcstrings</strong> is not included into the main target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*Uo5YAq-GMOUrRXd1TsTF0g.png" /></figure><p>Now we can preview the localisation like in previous version.</p><h4>Conclusion</h4><p>We can follow multiple approaches to test translation separately from the main application. One is different file naming and using code to load specific string catalog, other one is using the same naming but defining Target membership for each resource to make sure each target load appropriate resources. From my own perspective the second approach is preferable because it does not require any code writing and irrelevant resource won’t be bundled into the final version of the app. However it could be difficult to identify the issue with file target membership if it appear due to problematic merge of pbxproj file.</p><h3>Let’s Connect!</h3><p>If you found this article helpful, let’s stay in touch:</p><ul><li><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/sergey-pekar/">linkedin.com/in/sergey-pekar</a></li><li><strong>Stack Overflow:</strong> <a href="https://stackoverflow.com/users/1677835/sergey-pekar">https://stackoverflow.com/users/1677835/sergey-pekar</a></li><li><strong>X (Twitter):</strong> <a href="https://twitter.com/sergey_pekar">@sergey_pekar</a></li></ul><p>I’m a Senior iOS developer from Poland with 14+ years of experience. If you’re looking for a skilled mobile developer who cares about performance and clean architecture and business value — let’s talk!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbfaef4aa4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>