<?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 Saad El Oulladi on Medium]]></title>
        <description><![CDATA[Stories by Saad El Oulladi on Medium]]></description>
        <link>https://medium.com/@saad-eloulladi?source=rss-d0e5a1b0502c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*039wGBXzAHCxg1UtIYX1KQ.jpeg</url>
            <title>Stories by Saad El Oulladi on Medium</title>
            <link>https://medium.com/@saad-eloulladi?source=rss-d0e5a1b0502c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:42:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saad-eloulladi/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[Protocols in Swift: some vs any (Opaque vs Existential)]]></title>
            <link>https://saad-eloulladi.medium.com/protocols-in-swift-some-vs-any-opaque-vs-existential-3b3771c39037?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b3771c39037</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-protocol]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 13:06:07 GMT</pubDate>
            <atom:updated>2026-07-23T13:06:07.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIsfZO-TIrdVqQP_0SgA0g.png" /></figure><p>When working with protocols in Swift, you’ll often face a subtle but important choice: should you return some Protocol or any Protocol?</p><p>At first glance, both seem to do the same thing : hide a concrete type behind a protocol.</p><p>But under the hood, they behave very differently, and that impacts performance, type safety, and API design.</p><p>Let’s break it down.</p><h3>The Setup</h3><pre>protocol Eatable {<br>    func eat()<br>}<br><br>struct Apple: Eatable {<br>    func eat() { print(&quot;Eating an apple&quot;) }<br>}<br><br>struct Banana: Eatable {<br>    func eat() { print(&quot;Eating a banana&quot;) }<br>}</pre><h3>Any: Existential Type</h3><pre>// ✅ Existential: can return different concrete types<br>func makeFood() -&gt; any Eatable {<br>    let i = Int.random(in: 0..&lt;2)<br>    if i == 0 {<br>        return Apple()<br>    } else {<br>        return Banana()<br>    }<br>}</pre><p><strong>What it means</strong></p><ul><li>any Alimentable is an <em>existential type</em></li><li>It’s essentially a box that can hold <em>any</em> value conforming to Alimentable</li></ul><p><strong>Key characteristics</strong></p><ul><li>The concrete type is erased at compile time</li><li>The caller only knows: “this is something that conforms to Alimentable”</li><li>Dynamic dispatch is used</li></ul><p><strong>Why use it</strong></p><ul><li>You need to return <em>different types</em> at runtime</li><li>You don’t care about the underlying concrete type</li><li>You want flexibility over performance</li></ul><h3>Using some — Opaque Type</h3><pre><br>// ✅ Opaque: must always return the SAME concrete type<br>func makeApple() -&gt; some Eatable {<br>    return Apple()<br>}</pre><p><strong>What it means</strong></p><ul><li>some Alimentable is an <em>opaque type</em></li><li>The function hides the concrete type from the caller, but the compiler still knows it</li></ul><p><strong>Important rule</strong></p><ul><li>You must return the <em>same concrete type</em> on every code path</li></ul><p>This would <strong>not compile</strong>:</p><pre>func invalidOpaque() -&gt; some Eatable {<br>    if Bool.random() {<br>        return Apple()<br>    } else {<br>        return Banana() // ❌ different concrete type<br>    }<br>}</pre><h3>Why some Matters</h3><p>Using some gives you strong advantages:</p><ul><li>Better performance: static dispatch instead of dynamic dispatch</li><li>Type preservation: the compiler still tracks the real type</li><li>Optimizations: known size and layout at compile time</li><li>Works well with generics and SwiftUI-style APIs</li></ul><p>This is why SwiftUI heavily relies on some View.</p><h3>Mental Model</h3><p>A simple way to think about it:</p><ul><li>any = “I can return <em>any</em> conforming type (I don’t care which)”</li><li>some = “I return <em>one specific type</em>, but I’m hiding it from you”</li></ul><h3>When to Use Which</h3><p>Use some when:</p><ul><li>You control the implementation</li><li>You always return the same concrete type</li><li>You want performance and compiler optimizations</li></ul><p>Use any when:</p><ul><li>You need runtime flexibility</li><li>You return multiple possible types</li><li>You explicitly want type erasure</li></ul><h3>Practical Insight</h3><p>If you’re designing APIs (especially in SwiftUI or modern Swift concurrency code), prefer some by default. Switch to any only when you actually need heterogeneity.</p><p>This small keyword choice directly impacts how your code performs and scales.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b3771c39037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Coordinator Pattern for SwiftUI (NavigationStack)]]></title>
            <link>https://saad-eloulladi.medium.com/the-coordinator-pattern-for-swiftui-navigationstack-7258b47dc00b?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7258b47dc00b</guid>
            <category><![CDATA[coordinator-pattern]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 15:10:33 GMT</pubDate>
            <atom:updated>2026-07-20T15:10:33.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQz3MrNSFy3G_jM_WKOm3A.png" /></figure><p>During the last years, SwiftUI has grown at a remarkable rate. Applications built with it were mainly small and contained generally few screens. While now they became gigantic, with navigation flows so complex.</p><p>In addition to the testability issues faced with the classic NavigationLink approach, the well known problem of views deciding their own navigation made people look for an alternative to be able to scale well SwiftUI applications.</p><p>Then the <strong>Coordinator pattern</strong>, popularized on iOS by Soroush Khanlou in his talk “The Coordinator” back in the UIKit days, started gaining interest again in the SwiftUI community. Searching for a better separation of concerns, and less coupling between screens.</p><p>The Coordinator is an abstract concept which is not related to a given UI framework. Taking the special context of SwiftUI into account, people at first were not sure how to apply it. Navigation state was scattered across isActive bindings and hidden NavigationLinks, which made programmatic navigation fragile at best.</p><p>Then with iOS 16, Apple introduced <strong>NavigationStack</strong>, driven by a simple array of paths. And suddenly, the Coordinator pattern found its natural home in SwiftUI.</p><p>What is exactly the benefit of adopting a Coordinator? How does NavigationStack make it possible? And is it really that simple to implement? Let&#39;s try to demystify all this step by step.</p><h3>What is a Coordinator</h3><p>Before jumping into the SwiftUI implementation, let’s discover first the Coordinator concept itself. And what are the benefits that it brings in an application in general.</p><p>The Coordinator pattern helps to address the following issues:</p><ul><li>Views become too dependent on each other. When FirstView creates and pushes SecondView directly, it must know about its existence, its initialization, and its parameters. With a Coordinator, we <strong>isolate all navigation decisions</strong> in a separate object.</li><li>Usually when you want to change a navigation flow, you need to hunt through views to find who pushes what. A Coordinator <strong>provides a good separation of concerns</strong>, so all the flow logic lives in one place.</li><li>The Coordinator <strong>makes navigation testable</strong>. Since navigation becomes plain data (an array of routes), you can assert on it in a unit test without rendering a single pixel.</li><li>Deep linking becomes trivial. Since the navigation state is just an array, restoring or constructing any flow means <strong>setting an array</strong>, nothing more.</li></ul><h3>The Dependency Rule</h3><p>An important rule about this pattern: <strong>views should know nothing about other views</strong>. A view expresses an <em>intent</em> (“go to the second screen”), and the Coordinator decides what that means concretely.</p><p><em>For instance, </em><em>SecondView should have no reference to </em><em>ThirdView. It only knows a </em><em>Route.</em></p><h3>NavigationStack, the missing piece</h3><p>For years, SwiftUI navigation was declared inline, inside the view hierarchy:</p><pre>NavigationLink(destination: SecondView()) {<br>    Text(&quot;Go to SecondView&quot;)<br>}</pre><p>Notice that here the view is deciding, creating, and presenting its destination. All at once. This is exactly the kind of coupling we are trying to escape.</p><p>NavigationStack changed the game with one simple idea: <strong>the navigation state is a value you own</strong>.</p><pre>NavigationStack(path: $paths) { ... }</pre><p>The path is just an array. Append to it, and SwiftUI pushes a screen. Remove from it, and SwiftUI pops. Empty it, and you are back to root. Navigation stopped being a side effect of the view tree, and became plain data.</p><p>And who is the best candidate to own that data? The Coordinator. 😊</p><h3>Let’s have some practice</h3><p>This is a small three-screen demo app. The user navigates from a first view to a second (passing a parameter), then to a third, with the possibility to pop back one screen or jump directly back to root.</p><p>The full project is available here: <a href="https://github.com/farabi/navigationstack_coordinator">NavigationStackCoordinator</a>.</p><h3>The Route</h3><p>First, we define a Route enum listing every possible destination of our flow:</p><pre>enum Route: Hashable {<br>  case secondView(param: String)<br>    case thirdView<br>    @ViewBuilder<br>    var destinationView: some View {<br>        switch self {<br>        case .secondView:<br>            SecondView()<br>        case .thirdView:<br>            ThirdView()<br>        }<br>   }<br>}</pre><p>Two things to notice here:</p><ul><li>The enum conforms to Hashable. This is required by NavigationStack, since the path elements must be hashable values.</li><li>Each case can carry <strong>parameters</strong>, like secondView(param: String). Passing data between screens becomes as natural as constructing an enum case.</li></ul><p>The destinationView computed property is the single place where a Route is transformed into an actual view. Views never instantiate other views anymore.</p><blockquote>Note that the Route is the contract between the views and the Coordinator. Views only manipulate Routes, and know nothing about the concrete destination views.</blockquote><h3>The Coordinator</h3><p>Now the central piece. And you might be surprised by how small it is:</p><p>swift</p><pre>final class Coordinator&lt;T: Hashable&gt;: ObservableObject {<br>    <br>    @Published var paths: [T] = []<br>    <br>    func push(_ path: T) {<br>        paths.append(path)<br>    }<br>    func pop() {<br>        paths.removeLast()<br>    }<br>    func popToRoot() {<br>       paths = []<br>    }<br>    func replacePath(_ paths: [T]) {<br>        self.paths = paths<br>    }<br>}</pre><p>That’s it. No UINavigationController reference, no delegate protocols, no child coordinator bookkeeping. The whole navigation engine of the app is a published array and four methods:</p><ul><li><strong>push:</strong> appends a route, SwiftUI pushes the corresponding screen.</li><li><strong>pop:</strong> removes the last route, SwiftUI pops the current screen.</li><li><strong>popToRoot:</strong> empties the array, SwiftUI unwinds the whole stack in one shot. Something that used to require ugly workarounds with NavigationView.</li><li><strong>replacePath:</strong> replaces the entire stack at once. This is your deep linking entry point. Want to open the app directly on the third screen? replacePath([.secondView(param: &quot;deeplink&quot;), .thirdView]) and you are done.</li></ul><p>Notice also that the Coordinator is <strong>generic</strong> over any Hashable type. It is not tied to our Route enum. This means the same class can drive multiple independent flows, each with its own route type.</p><h3>Plugging everything together</h3><p>The root view owns the Coordinator as a @StateObject, binds its paths to the NavigationStack, and injects it in the environment:</p><p>swift</p><pre>struct ContentView: View {<br>    <br>    @StateObject var coordinator = Coordinator&lt;Route&gt;()<br>    <br>    var body: some View {<br>        /// ⚠️ A Router view could be used to wrap NavigationStack<br>        /// We kept it here to demonstrate the issue<br>        NavigationStack(path: $coordinator.paths) {<br>            VStack {<br>                Text(&quot;This is the first view 1️⃣!&quot;)<br>                Button(&quot;Go to SecondView&quot;) {<br>                    coordinator.push(.secondView(param: &quot;Some param&quot;))<br>                }<br>            }<br>            .padding()<br>            .navigationDestination(for: Route.self) { $0.destinationView }<br>        }.environmentObject(coordinator)<br>    }<br>}</pre><p>Three key lines here:</p><ol><li>NavigationStack(path: $coordinator.paths) : the stack is now entirely driven by the Coordinator&#39;s array.</li><li>.navigationDestination(for: Route.self) { $0.destinationView } : whenever a Route lands in the path, SwiftUI asks the route itself for its destination. One single mapping point for the whole flow.</li><li>.environmentObject(coordinator) : every pushed view can access the Coordinator without any manual wiring.</li></ol><p>And here is what a child view looks like:</p><pre>struct SecondView: View {<br>    <br>    @EnvironmentObject var coordinator: Coordinator&lt;Route&gt;<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;This is the second 2️⃣!&quot;)<br>            Button(&quot;Go to third view&quot;) {<br>                coordinator.push(.thirdView)<br>            }<br>            Button(&quot;Back&quot;) {<br>                coordinator.pop()<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><p>The view expresses intents (push, pop), and nothing else. It does not create ThirdView, it does not know how it is initialized, it does not even know it exists.</p><p>Remember: <strong>“Only UI code”</strong> in the views. Navigation belongs to the Coordinator.</p><h3>What’s wrong with this implementation</h3><p>When understanding how this really works, we may think that separation of concerns could not be better applied. Although this is a solid foundation, it is far from being perfect. Here’s why:</p><ul><li><strong>The root view is still doing too much.</strong> You may have noticed the ⚠️ comment in ContentView: it declares its own content, hosts the NavigationStack, owns the Coordinator, and declares the destination mapping. A dedicated <strong>Router view</strong> wrapping the NavigationStack would restore the symmetry, making the first screen a regular view like the others.</li><li><strong>The Route builds the views.</strong> Putting destinationView inside the enum is convenient, but it means our navigation model imports SwiftUI. In a stricter clean architecture spirit, the Route should stay a pure value, and the view mapping should live on the framework side.</li><li><strong>Presentation is not covered.</strong> This Coordinator drives the push stack only. Sheets and full screen covers have their own presentation state, and a complete solution should model them too.</li><li><strong>pop() will crash on an empty path.</strong> removeLast() on an empty array is a runtime error. A production Coordinator should guard against it.</li></ul><p>None of these are flaws of the pattern itself. They are the natural next iterations of it, exactly like VIP was a next iteration of VIPER.</p><h3>Conclusion</h3><p>In the same way that clean architectures can make a big project well organised and structured, we should always keep in mind that navigation deserves the same care we give to our business logic. NavigationStack finally gives us navigation as data, and the Coordinator gives that data an owner.</p><p>Another point to take into account is the project scale. In many cases, when having a small application with two or three screens, plain NavigationLink is more than enough.</p><p>Always remember that there is no architecture that matches all the cases.</p><p>Sure in the future, new navigation APIs will appear with new enhancements, this is how things evolve. Till then, let’s keep our navigation coordinated. 😊</p><p>Thank you for reading. 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7258b47dc00b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Take Your Continuous Integration to Another Level Using AI]]></title>
            <link>https://saad-eloulladi.medium.com/take-your-continuous-integration-to-another-level-using-ai-63da82e8fc84?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/63da82e8fc84</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[changelog]]></category>
            <category><![CDATA[qwen-3]]></category>
            <category><![CDATA[continous-integration]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 21:05:23 GMT</pubDate>
            <atom:updated>2026-07-20T14:21:04.102Z</atom:updated>
            <content:encoded><![CDATA[<p>Vibe coding is starting to take over the dev community. Some developers see it as a blessing, others are still unsure if it’s good or bad. Maybe the truth lies somewhere in between, it all depends on how we use it.</p><p>The biggest limit in CI is that you don’t always have a <strong>universal rule</strong> you can just write a script for. That’s where AI comes in with the extra intelligence needed for those tricky cases.<br>Take <strong>changelogs</strong> for example: yes, there are tools for automatic changelog generation, but they usually depend on strict rules like well-structured commit messages, Gitflow conventions, and other predefined formats. AI, on the other hand, can analyze your history in a more flexible way and generate useful documentation without forcing you into one rigid workflow.</p><p>That’s where tools like <a href="https://github.com/QwenLM/qwen-code">Qwen Code</a> come in: Qwen is an open-source AI coding assistant “Agentic code model” that you can install and run right from your terminal.</p><h3>Getting Started with Qwen Code</h3><p>Here’s how you can quickly set it up and integrate it into your workflow:</p><h4><strong>Make sure you have npm installed</strong></h4><pre>node -v <br>npm -v</pre><h4><strong>Install Qwen Code</strong></h4><pre>npm install -g @qwen-code/qwen-code@latest</pre><h4><strong>Log in to Qwen</strong></h4><p>Running the qwen command opens an <strong>interactive CLI</strong>.</p><p>The first time you run it, you will be asked to <strong>log in</strong>. This step is required so the CLI can authenticate your account before executing prompts.</p><p>Think of it as a terminal chat with an AI coding assistant. You can type natural language instructions like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piHoTrLDBqYcGFCV24fAfA.png" /></figure><h4><strong>Generate a changelog or readme</strong></h4><pre>qwen -y true -p &quot;generate a short readme and save it in the project root&quot;</pre><ol><li>The -y true flag automatically accepts the authentication request.</li><li>The -p for the prompt.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GB2FpWsqwlgnrOgrZQZiQ.png" /></figure><p>From here, you can easily drop this command inside your CI pipeline so every new release comes with a clean, automatically generated changelog or documentation update.</p><h3>What About Privacy Concerns?</h3><p>Some companies don’t allow sending project data to external LLMs. That’s a valid concern. The good news is you can still use <strong>local AI models</strong> that run completely on your machine. Tools like <a href="https://lmstudio.ai/">LM Studio</a> let you run models offline, keeping your code private while still benefiting from automation.</p><h3>Final Thoughts</h3><p>AI is not here to replace developers, but it can definitely reduce the repetitive tasks that slow us down. Automating changelog generation in CI is just one example. With tools like Qwen Code, you can make your pipeline smarter, your releases cleaner, and your team more focused on the work that really matters.</p><p>Stay tuned , next time, we’ll explore running local AI models for maximum privacy.</p><h3>References</h3><ul><li><a href="https://lmstudio.ai/">LM Studio</a></li><li><a href="https://cline.bot/blog/local-models">Cline Bot — Local Models Blog</a></li><li><a href="https://github.com/QwenLM/qwen-code">Qwen Code GitHub Repository</a></li><li><a href="https://dev.to/therealmrmumba/how-to-use-qwen3-coder-and-qwen-code-4g4p">How to use Qwen3 Coder and Qwen Code — Dev.to</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63da82e8fc84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Vibe Coding Isn’t Going to Replace Developers Anytime Soon]]></title>
            <link>https://saad-eloulladi.medium.com/why-vibe-coding-isnt-going-to-replace-developers-anytime-soon-004f858eb1f5?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/004f858eb1f5</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 12:41:59 GMT</pubDate>
            <atom:updated>2025-08-28T12:41:59.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*xSwTOULTADLegZ-bLeW9VQ.png" /></figure><p>If you’ve experimented with “vibe coding” — giving natural language prompts to AI to generate applications — you’ve probably noticed that it works surprisingly well for demos, prototypes, or MVPs. But once you step into the world of production software, things start to fall apart. Why?</p><h4>1. The Need for Real Understanding</h4><p>Programming languages aren’t just a set of instructions for machines. They’re carefully designed abstractions that take the messy, ambiguous nature of human language and reduce it to something a computer can interpret. Large language models (LLMs), on the other hand, don’t actually “understand” what they generate. They predict text patterns. Explaining nuanced business logic to an AI often ends up being as difficult as — if not harder than — writing the code yourself.</p><h4>2. The Quality of AI’s Training Data</h4><p>AI models are trained on vast amounts of code, far more than any developer could read in a lifetime. But more data doesn’t always mean better. Much of the code on the internet is mediocre or context-specific, and “good code” itself can mean different things depending on performance, security, scalability, or readability requirements. A human developer knows when and why to apply best practices — AI does not.</p><h4>3. The Value of Real Developers</h4><p>AI can automate repetitive tasks, boilerplate, or glue code. It will certainly reduce the need for developers whose work is limited to copying and pasting snippets. But experienced developers — the ones who can think critically, model complex business processes, and make trade-offs — remain essential. They bring context, judgment, and long-term vision, none of which can be automated away by a predictive model.</p><h3>Conclusion</h3><p>AI coding tools are impressive, and they’re already changing how we build software. But they aren’t replacing real developers anytime soon. Instead, they’ll become powerful assistants, helping developers focus on higher-level thinking while the machine handles the grunt work. The jobs most at risk aren’t those of skilled engineers, but of anyone whose “development” work is little more than mechanical repetition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=004f858eb1f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI List vs LazyVStack: The real difference]]></title>
            <link>https://saad-eloulladi.medium.com/swiftui-list-vs-lazyvstack-the-real-difference-f2e56d3b8adf?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e56d3b8adf</guid>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 18:44:30 GMT</pubDate>
            <atom:updated>2025-08-28T15:17:50.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DYXDG7RcxypP8XAvURGRw.png" /></figure><p>👋 <strong>Dear iOS developer, we need to talk about the SwiftUI </strong><strong>List.</strong></p><p>If you’re coming from a UIKit background, like me, you probably assumed that List in SwiftUI is the direct equivalent of UITableView. After all, it even appears in Xcode’s UI debugger as a wrapper over UITableView on iOS 13–15, and UICollectionView from iOS 16 onward. That implied one thing: <strong>List should have performance benefits thanks to view reuse</strong>, whereas LazyVStack doesn’t.</p><p>Right? Well… not quite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*BYHJT8gWMMx_BhJFI0DrKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*dlD5oh9TmFV4dvy29RjNLg.png" /></figure><h3>What the Articles Say</h3><p>Many tutorials and articles on this topic focus on extra features rather than the core difference. Donny Wals, for example, explains differences mostly in terms of <strong>styling, swipe actions, and edit mode</strong>:<br> <a href="https://www.donnywals.com/choosing-between-lazyvstack-list-and-vstack-in-swiftui/">https://www.donnywals.com/choosing-between-lazyvstack-list-and-vstack-in-swiftui/</a></p><p>But is that everything, Isn’t there a performance benefit?</p><p>What about <strong>actual performance under the hood</strong>? That’s what I wanted to find out.</p><p>STRV also did a great job in <a href="https://www.strv.com/blog/swiftui-list-vs-lazyvstack">that article</a>, benchmarking List and LazyVstack performance.</p><p>I ran my own tests too — tracking memory usage, row initialization, and scrolling performance… <br>The main point i noticed that even “not always” list outperformed LazyVstack, there is no huge decisive advantage of List over LazyVstack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEpubPrgUBdX-w08Oqd_lQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8L3xd1xWP6v48z-6DPo7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DYXDG7RcxypP8XAvURGRw.png" /></figure><p>Even Apple documentation does notmention any performance benefit of List. <br>: Apple documentation mentions using `List` when you need <strong>swipe-to-delete, edit, or drag-and-drop</strong>.</p><p>but is that all what list should be used for 🤯 😂 ? <a href="https://developer.apple.com/documentation/swiftui/displaying-data-in-lists"><br>documentation says </a>:</p><blockquote>“If you want to remove the platform-appropriate styling — such as row separators or automatic disclosure indicators — from your list, consider using LazyVStack instead. For more information on working with lazy stacks, see Creating performant scrollable stacks”</blockquote><p>So it seems styling, not performance, is the main factor in Apple’s recommendation.</p><h3>Why This Feels Weird</h3><p>List started as a UITableView wrapper — perfect for UIKit’s imperative world, with clear reuse benefits. But SwiftUI is declarative, and declarative programming <strong>doesn’t map perfectly to UITableView’s paradigms</strong>.</p><p>From iOS 16 onwards, List switched to using UICollectionView under the hood, but Apple doesn’t clearly explain how reuse works anymore. Most tutorials gloss over this entirely, focusing on features rather than performance.</p><h3>The Main Takeaway</h3><p>💡 Here’s what I concluded:</p><ul><li>List is <strong>not automatically faster</strong> than LazyVStack.</li><li>Use List if you need features inherited from UIKit — swipe actions, edit mode, drag-and-drop.</li><li>Otherwise, LazyVStack is simpler, flexible, and performs almost the same.</li><li>In other words, List now feels like an <strong>abandoned UIKit relic</strong> quietly replaced by LazyVStack in modern SwiftUI.</li></ul><h3>Final Thoughts</h3><p>SwiftUI is evolving fast, and sometimes what we assume is “better” performance is just a leftover from UIKit. Always test for your own use case, and don’t blindly assume that List is the most efficient choice.</p><h3><strong>References</strong>:</h3><ul><li><a href="https://swiftwithmajid.com/2025/03/04/swiftui-performance-how-to-use-uikit/">https://swiftwithmajid.com/2025/03/04/swiftui-performance-how-to-use-uikit/</a></li><li><a href="https://nilcoalescing.com/blog/CustomLazyListInSwiftUI/?utm_source=substack&amp;utm_medium=email">https://nilcoalescing.com/blog/CustomLazyListInSwiftUI/?utm_source=substack&amp;utm_medium=email</a></li><li><a href="https://www.strv.com/blog/swiftui-list-vs-lazyvstack">https://www.strv.com/blog/swiftui-list-vs-lazyvstack</a><br><a href="https://stackoverflow.com/questions/77532990/make-swiftui-list-view-reusable">https://stackoverflow.com/questions/77532990/make-swiftui-list-view-reusable</a></li><li><a href="https://dimillian.medium.com/swiftui-the-difference-between-list-and-lazyvstack-3d5eeaccb156">https://dimillian.medium.com/swiftui-the-difference-between-list-and-lazyvstack-3d5eeaccb156</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e56d3b8adf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid These Mistakes When Working with Swift Actors]]></title>
            <link>https://saad-eloulladi.medium.com/avoid-these-mistakes-when-working-with-swift-actors-1aaa739a109f?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aaa739a109f</guid>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 22:30:44 GMT</pubDate>
            <atom:updated>2025-02-24T22:30:44.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thread Safety: A Big Challenge in Programming</h3><p>Concurrency is tricky. When multiple threads try to access shared data at the same time, things can go wrong. This can lead to problems like data corruption or crashes.</p><p>Over the years, developers have used different techniques to handle this.</p><p>For example, in Swift, you can use locks to protect parts of your code:</p><pre>let lock = NSLock()  <br>var counter = 0<br><br>func incrementCounter() {  <br>  lock.lock()  <br>  defer { lock.unlock() }  <br>  counter += 1  <br>}</pre><p>Or you can use semaphores to control how many threads can access something at once:</p><pre>let semaphore = DispatchSemaphore(value: 1)<br><br>func performTask() {  <br>  semaphore.wait()  <br>  defer { semaphore.signal() }  <br>  // Do something important here  <br>}</pre><p>Grand Central Dispatch (GCD) is another tool that helps manage threads. You can create a queue to run tasks one at a time:</p><pre>let serialQueue = DispatchQueue(label: “com.example.serial”)  <br>serialQueue.async {  <br>  // Do something important here  <br>}</pre><p>These tools work well, but they can be hard to use correctly.</p><p>If you’re not careful, you might end up with issues like deadlocks or race conditions.</p><h3>Actors</h3><p>To make concurrency safer, Apple introduced <strong>actors</strong> in Swift. Actors help manage shared data safely without needing locks or semaphores. Here’s how they work:</p><ol><li><strong>Actor Isolation</strong>: Each actor has its own data. Only one task can change the actor’s data at a time.</li><li><strong>Message Passing</strong>: Tasks send messages to actors. The actor handles these messages one by one.</li><li><strong>Asynchronous Execution</strong>: Actors use async/await to handle long-running tasks without blocking the app.</li></ol><p>This makes actors safer and easier to use than traditional methods. But they come with their own challenges… like reentrancy.</p><h3>What Is Reentrancy?</h3><p>Reentrancy happens when an actor pauses during an await. While it’s paused, other tasks can run and change the actor’s data. This can cause unexpected problems.</p><p>Let’s look at three common issues caused by reentrancy:</p><h4>1. Mutable State Changes</h4><p>Sometimes, one task changes the actor’s data while another task is paused. This can lead to incorrect results.</p><p>Here’s an example of an OrderProcessor actor that manages inventory:</p><pre>actor OrderProcessor {<br>    var inventory: [String: Int] = [&quot;Laptop&quot;: 1]<br><br>    func placeOrder(item: String, quantity: Int) async throws {<br>        guard let stock = inventory[item], stock &gt;= quantity else {<br>            throw NSError(<br>                domain: &quot;InventoryError&quot;,<br>                code: 1,<br>                userInfo: [NSLocalizedDescriptionKey: &quot;Out of stock&quot;]<br>            )<br>        }<br>        <br>        try await Task.sleep(nanoseconds: 1_000_000_000)<br>        inventory[item] = stock - quantity<br>        print(&quot;Order placed: \(item) x \(quantity)&quot;)<br>    }<br>}</pre><p>If two tasks try to buy the last laptop:</p><pre>let processor = OrderProcessor()<br><br>Task {<br>    do {<br>        try await processor.placeOrder(item: &quot;Laptop&quot;, quantity: 1)<br>    } catch {<br>        print(&quot;Error: \(error.localizedDescription)&quot;)<br>    }<br>}<br><br>Task {<br>    do {<br>        try await processor.placeOrder(item: &quot;Laptop&quot;, quantity: 1)<br>    } catch {<br>        print(&quot;Error: \(error.localizedDescription)&quot;)<br>    }<br>}</pre><p>Output:</p><pre>Order placed: Laptop x 1  <br>Error: Out of stock</pre><p>The second task resumes after the first task has already changed the inventory. This can cause problems if not handled carefully.</p><h4>How to fix it</h4><p>Avoid checking the status before long tasks. If possible, skip verifying the state beforehand, as it may become outdated during the task due to reentrancy.</p><p>If necessary, check the status both before and after the waiting task.</p><pre>actor OrderProcessor {<br>    var inventory: [String: Int] = [&quot;Laptop&quot;: 1]<br><br>    func placeOrder(item: String, quantity: Int) async throws {<br><br>        try await Task.sleep(nanoseconds: 1_000_000_000) // wait before <br><br>        guard let stock = inventory[item], stock &gt;= quantity else {<br>            throw NSError(<br>                domain: &quot;InventoryError&quot;,<br>                code: 1,<br>                userInfo: [NSLocalizedDescriptionKey: &quot;Out of stock&quot;]<br>            )<br>        }<br>        <br>        <br>        inventory[item] = stock - quantity<br>        print(&quot;Order placed: \(item) x \(quantity)&quot;)<br>    }<br>}</pre><h4>2. Double Computations</h4><p>Reentrancy can also cause the same task to run twice. For example, if two tasks calculate the same discount:</p><pre>actor OrderProcessor {<br>    var cachedDiscounts: [String: Double] = [:]<br><br>    func calculateDiscount(forItem item: String, price: Double) async -&gt; Double {<br>        if let cachedDiscount = cachedDiscounts[item] {<br>            return cachedDiscount<br>        }<br><br>        print(&quot;Calculating discount for \(item)…&quot;)<br>        try? await Task.sleep(nanoseconds: 1_000_000_000)<br>        let discount = price * 0.1<br><br>        cachedDiscounts[item] = discount<br>        return discount<br>    }<br>}</pre><p>If two tasks calculate the discount for the same item:</p><pre>let processor = OrderProcessor()<br><br>Task {<br>    let discount = await processor.calculateDiscount(forItem: &quot;Laptop&quot;, price: 1000.0)<br>    print(&quot;Discount: \(discount)&quot;)<br>}<br><br>Task {<br>    let discount = await processor.calculateDiscount(forItem: &quot;Laptop&quot;, price: 1000.0)<br>    print(&quot;Discount: \(discount)&quot;)<br>}</pre><p>Output:</p><pre>Calculating discount for Laptop…  <br>Calculating discount for Laptop…  <br>Discount: 100.0  <br>Discount: 100.0</pre><p>Both tasks calculate the discount separately, wasting time and resources.</p><h3>How to Fix</h3><p>This could be fixed by storing the task in the cache before awaiting it, And reuse the existing task instead of creating a new one.</p><pre>actor OrderProcessor {<br><br>    private var cachedDiscounts: [String: Task&lt;Double, Error&gt;] = [:]<br><br>    func calculateDiscount(forItem item: String, price: Double) async throws -&gt; Double {<br>        // Check if there&#39;s an existing task for this item<br>        if let task = cachedDiscounts[item] {<br>            return try await task.value // Reuse the existing task<br>        }<br><br>        // Create a new task to calculate the discount<br>        let task = Task {<br>            try await computeDiscount(forItem: item, price: price)<br>        }<br><br>        cachedDiscounts[item] = task<br><br>        return try await task.value<br>    }<br><br>    private func computeDiscount(forItem item: String, price: Double) async throws -&gt; Double {<br>        print(&quot;Calculating discount for \(item)...&quot;)<br>        try await Task.sleep(nanoseconds: 1_000_000_000)<br>        let discount = price * 0.1<br>        print(&quot;Discount calculated for \(item): \(discount)&quot;)<br>        return discount<br>    }<br>}</pre><p>Output:</p><pre>Calculating discount for Laptop...<br>Discount calculated for Laptop: 100.0<br>Discount: Optional(100.0)<br>Discount: Optional(100.0)</pre><h3>Conclusion</h3><p>Actors are a great way to handle concurrency in Swift. They make it easier to manage shared data without worrying about locks or semaphores. But reentrancy can cause problems if you’re not careful. By understanding these issues and using best practices, you can write safer and more efficient code. Actors are a powerful tool for building modern apps, and with practice, you’ll get better at using them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aaa739a109f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to VisionOS Development]]></title>
            <link>https://saad-eloulladi.medium.com/introduction-to-visionos-development-617b8c9b9f92?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/617b8c9b9f92</guid>
            <category><![CDATA[spacial-computing]]></category>
            <category><![CDATA[visionos-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[realitykit]]></category>
            <category><![CDATA[apple-vision-pro]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 16:13:39 GMT</pubDate>
            <atom:updated>2024-04-02T12:55:34.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2LNHj-UFY3uzMjMyWnFvA.png" /></figure><h3>Introduction</h3><p>Regardless of one’s opinions on Apple’s role in the tech industry today, it’s impossible to overlook the criticisms. These include the perceived stagnation in innovation with recent iPhone models, debates around planned obsolescence driving consumers to purchase new versions, and the increasing difficulty for users to repair their devices. The list of grievances could go on.</p><p>However, one of the important aspects that drew me to iOS development over a decade ago, is Apple’s introduction of the iPhone.</p><p>For better or worse, it has fundamentally shaped our current world. It’s undeniable that while mobile internet and touchscreen technology existed long before the iPhone, Apple’s mastery in integrating these technologies with its robust software ecosystem, truly revolutionised the user experience. This holistic approach was nothing short of genius, setting Apple years ahead of its competition at the time.</p><p>At 2023 Apple’s Worldwide Developers Conference, a groundbreaking mixed-reality headset named VisionPro was unveiled. Apple is taking a step beyond traditional augmented reality headsets by introducing what it calls ‘Spatial computing’. This means using the space around you as your computer interface, not just screens, which has been the norm until now.</p><p>What truly excites me about Apple’s VisionPro isn’t just the typical ‘wow’ effect that comes with new AR headsets. What stands out to me is how Apple seems to be returning to its core philosophy: pushing consumers out of their comfort zones by heavily investing in new, risky technologies and challenging established user habits.</p><p>With VisionPro, Apple is navigating a challenging terrain — a field where other tech giants have previously stumbled. We’ll delve into why Apple’s VisionPro might either succeed or falter in a later discussion. But taking into account the amount of technology and innovation apple invested in the visionOS, it’s evident that this venture is far from a reckless risk on Apple’s part.</p><p>In the subsequent sections of this article, we’ll explore the fundamentals of Apple’s VisionOS development. This will serve as an excellent start for those looking to deepen their understanding of VisionOS development and Apple’s innovative approach.</p><h3>Requirements</h3><p>Developing for VisionOS requires :</p><ul><li>Xcode 15 beta 2 or later</li><li>Apple silicon processor</li></ul><h4>New project</h4><p>In this article, we’ll take a practical approach to explore VisionOS. So, without further ado, let’s create a new VisionOS app project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*YarP9lHhAoczWWNr9I9ahA.png" /></figure><p>Choose any project name you want, then select Initial Scene as Windows, and mixed immersive space. We will see later in this article that setting these parameters for a new project allows modifying the project template in a way we will be able to understand and do manually.</p><blockquote>ℹ️ We can use either RealityKit or Metal as the immersive space renderer. Metal is a low-level, hardware-accelerated graphics framework that uses C++. We can also use it for building immersive spaces; however, this will not be covered within this article.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*0ymPdn_FC4fGDBns-_WNZw.png" /></figure><p>Once the project is created, it should look like this, with the app’s main file, a ContentView, an ImmersiveView, and a RealityKitContent package. Now that we have our project ready, we can go back and look at each part in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*_8xoN8AA92M1Ahib2EzFLw.png" /></figure><h4>USD File Formats</h4><p>Stands for Universal Scene Description. These are universal file formats developed by Pixar designed to facilitate the interchange and manipulation of 3D content.<br><strong>USDZ:</strong> A zero-compression, unencrypted zip archive that can package various file types, including usd, usda, usdc, png, jpeg, m4a, mp3, and wav files. The .usdz format is particularly tailored for sharing and distributing 3D assets seamlessly across platforms, especially within the Apple ecosystem.<br>You can create a model with your preferred 3D modeling software (3ds Max, Maya, Blender…) and import it as a USD* file into your VisionOS application. Or you can find ready-to-use 3D models on sites like sketchfab.com.<br>For this tutorial, I will download a sofa USDZ model file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nm862bi2YqUDWmtyqZpXvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*scit-R9zP-mkIAqKcA2M-Q.png" /></figure><h4>Reality Composer Pro</h4><p>Our project contains a RealityKitContent package, this package is meant to wrap all RealityKit-related content, such as images, 3D models, and other assets like audio and video files. Think of it as a 3D interface builder.<br>The RealityKitContent package also contains a Package.realitycomposerpro file, which is a RealityComposer Pro project.<br>Reality Composer Pro allows visually preparing, editing, animating, and previewing RealityKit content.</p><blockquote>⚠️ Important note: Reality Composer Pro is not a 3D modeling software, which means you need to create your models elsewhere and import them into it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*CWorYbNxghFQIE2uwFZKFQ.png" /></figure><p>Drag you Sofa.usdz file into the project browser section. this will allow to add it as an asset to be used in the reality composer project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*EMh5McgTafnY1pwBCWv4FQ.png" /></figure><p>Select the two Spheres and remove them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*woxDVqCOuhy2VcnGD9O65Q.png" /></figure><p>Grad the sofa in our scene, set Y position to zero, y rotation to 90, Z position to -191 so that it faces the user and scale it 0.003.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*Zrj_W62STLKFa_uHdC_zEQ.png" /></figure><p>Do the same for Scene inside RealityKitContent, but</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAy2LfVa8Lhspp4rnqXtSA.png" /></figure><p>In order to make our sofa respond to gestures, we need to add to it collision and input target components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-7OgQpcSZJAlYqXefqY_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsjZAmdFq53npKQf_8dJnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOUbSbclwHTYIw4zxSEBPA.png" /></figure><p>Let’s look into our App file, The first component declared in the App body is a WindowGroup than contains a ContentView. visionOS will consider this window the entry point of the application.</p><p>Hold on, what is a window ?</p><pre>import SwiftUI<br><br>@main<br>struct VisionOSDemoApp: App {<br>    var body: some Scene {<br>        <br>        // The first component to be declared in the App body<br>        // Will be considered as the main window <br>        WindowGroup {<br>            ContentView()<br>        }<br>  <br>        ImmersiveSpace(id: &quot;ImmersiveSpace&quot;) {<br>            ImmersiveView()<br>        }<br>    }<br>}</pre><h3>Windows</h3><p>Similar to iOS or macOS window, apps in their use and integration of SwiftUI. A window renders the content of a SwiftUI view on a 2D surface. However, it distinguishes itself from iOS or macOS views by incorporating a 3D depth element.</p><p>This allows for the addition of 3D objects within the app’s interface, although such objects are designed to complement the 2D surface without overwhelming it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*b8ChVaZ1oVMCS2EYd-dvKg.png" /></figure><p><strong>Can we control the position of a window ?</strong></p><p>No, in order to prevent intrusive behaviors, the system prevent developers from controlling the windows position.</p><p>The user then will be able to place the window where ever he wants i his environment.</p><p>Even the ‘defaultPosition’ window modifier is unavailable in visionOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*LBLaicLm8rXp5WGYjR7vbw.png" /></figure><p><strong>Can we control the size of a window ?</strong></p><p>Yes, we can set the default size using the defaultSize modifier, and we can specify the the resizability settings using windowResizability modifier.</p><p>Then the user also will also be able to resize the windows as he wishes, (or not depending the windowResizability …)</p><p>Checl <a href="https://developer.apple.com/documentation/swiftui/windowresizability">windowResizability documentation</a> for more informations</p><p><strong>Can we have multiple Windows in a VisionOS App ?</strong></p><p>A visionOS app can display many windows by having “Enable Multiple Windows” set to yes in the info.list</p><p>Replace ContentView with the following.</p><pre>import SwiftUI<br>import RealityKit<br>import RealityKitContent<br><br>struct ContentView: View {<br><br>    @State private var isShowWindow = false<br><br>    @Environment(\.openWindow) private var openWindow<br>    @Environment(\.dismissWindow) private var dismissWindow<br><br>    var body: some View {<br>        VStack {<br>            <br>            Text(&quot; Flips the visibility of a Volumetric window. If the toggle is on, the window is meant to be visible.&lt;br/&gt; when off, it suggests hiding the window&quot;)<br>            <br>            Toggle(isShowWindow ? &quot;HideWindow&quot; : &quot;ShowWindow&quot;, isOn: $isShowWindow)<br>                .onChange(of: isShowWindow) { isShowing, initial in<br>                    Task {<br>                        if !isShowing {<br>                            openWindow(id: &quot;volumetric-window&quot;)<br>                        } else {<br>                            dismissWindow(id: &quot;volumetric-window&quot;)<br>                        }<br>                    }<br>                }<br>                .toggleStyle(.button)<br>                .padding(25)<br>        }<br>    }<br>}</pre><p>We can see that our view contains regular SwiftUI views like Text and and toogle, what is different thow, the use of openWindow and dismissWindow environment.</p><p>This allows to open or close an other window by it’s ID,</p><p><strong>Okay, but where was this window declared, and what is a “volumetric-window” ?</strong></p><h3>Volumes</h3><p>Add a new window our app file. notice that this time our windowGroup has the same ID that we called in the first window, further more, it has a windowStyle modifier set to volumetric, which indicate that this is a Volume , not a Window,</p><pre><br>@main<br>struct VisionOSDemoApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        <br>        WindowGroup(id: &quot;volumetric-window&quot;) {<br>            VolumetricWindow()<br>        }<br>        .windowStyle(.volumetric)<br>    }<br>}<br></pre><p>Unlike a regular window, a volume takles 3D space, in which it can display 3D objects, move them and interact with user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*6tdk__2K7b9CUuXotMYIdQ.png" /></figure><p><strong>Can we control the size of a volume ?</strong></p><p>Yes, we can set a default size of a volume, however, once displayed, The volume maintains it’s size for its entire lifetime. even the user can’t change the size of a volume at runtime.</p><p>Now let’s see the implementation of our VolumetricWindow.</p><pre>struct VolumetricWindow: View {<br>    <br>    @State var entity: Entity?<br><br>    var body: some View {<br>        if let entity {<br>            DraggableEntity(entity: entity)<br>        } else {<br>            ProgressView()<br>                .progressViewStyle(.circular)<br>                .controlSize(.large)<br>                .task {<br>                    do {<br>                        entity = try await Entity(named: &quot;Scene&quot;,<br>                                                  in: realityKitContentBundle)<br>                        <br>                    } catch {<br>                        fatalError(&quot;Failed to load Scene&quot;)<br>                    }<br>                }<br>        }<br>    }<br>}</pre><pre><br>struct DraggableEntity: View {<br>    <br>    var entity: Entity<br>    <br>    @State private var sourceTransform: Transform?<br>    <br>    var body: some View {<br>        RealityView { content in<br>            content.add(entity)<br>        }.gesture(<br>         DragGesture()<br>             .targetedToEntity(entity)<br>             .onChanged { value in<br>                 if sourceTransform == nil {<br>                     sourceTransform = entity.transform<br>                 }<br>                 var convertedTranslation = value.convert(value.translation3D, from: .local, to: entity.parent!)<br>                 convertedTranslation.y = 0<br>                 entity.transform.translation = sourceTransform!.translation + convertedTranslation<br>             }<br>             .onEnded { _ in<br>                 sourceTransform = nil<br>             }<br>        )<br>    }<br>}</pre><p>We can see that the root view is a RealityView, which is a SwiftUI view thatwraps Reality content. to that we added a grad Gesture that allows us to move the RealityView,</p><p>Now let’s test that</p><p>Great , now our vulume window is displayed, and we wan move it using gestrure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jkiGgmnr1z9pzXeYwLHTg.png" /></figure><p>Wait, why the sofa becomes is truncated once we reach certain part.</p><p>Well beceause as we said for, the volume size is limited, and we can move content in it beyon it’s size.</p><p>And to move 3D objects freely, we need Immersive spaces for that.</p><h3>Immersive spaces</h3><p>In a non immersive experience each window and volume size and position is strictly controlled by the system.</p><p>An ImmersiveSpace in the other hand, allows us to use the so called “Shared Space”, enabling applications to use the entire shared space to position 3D objects freely or create custom environments for users.</p><blockquote>⚠️ An immersive space, dosn’t necessarily mean to change the user environment. We can start talking about an immersive space once we position an object in “Shared Space”</blockquote><p>Let’s see show to make an immersive space in our app.</p><pre><br>struct ContentView: View {<br><br>    @State private var showImmersiveSpace = false<br>    @State private var immersiveSpaceIsShown = false<br><br>    @Environment(\.openImmersiveSpace) private var openImmersiveSpace<br>    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace<br><br>    var body: some View {<br>        VStack {<br>            <br>            Text(&quot;Manages the display of an immersive space. Turning the toggle on tries to open the space, and switching it off leads to its dismissal.&quot;)<br><br>            Toggle(showImmersiveSpace ? &quot;HideImmersiveSpace&quot; : &quot;ShowImmersiveSpace&quot;, isOn: $showImmersiveSpace)<br>                .onChange(of: showImmersiveSpace) { isShowingImmersiveSpace, initial in<br>                    Task {<br>                        if !isShowingImmersiveSpace {<br>                            switch await openImmersiveSpace(id: &quot;immersive-space&quot;) {<br>                            case .opened:<br>                                immersiveSpaceIsShown = true<br>                            case .error, .userCancelled:<br>                                fallthrough<br>                            @unknown default:<br>                                immersiveSpaceIsShown = false<br>                                showImmersiveSpace = false<br>                            }<br>                        } else if immersiveSpaceIsShown {<br>                            await dismissImmersiveSpace()<br>                            immersiveSpaceIsShown = false<br>                        }<br>                    }<br>                }<br>                .toggleStyle(.button)<br>                .padding(25)<br>        }<br>    }<br>}</pre><p>Similarily to what we did to open a window here we use openImmersiveSpace environment to by passing the id of the Space we want to open. And dismissImmersiveSpace environment to close the immersive space.</p><p>No need to specify the ID when using dismissImmersiveSpac for closing.</p><pre>@main<br>struct VisionOSDemoApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        <br>        ImmersiveSpace(id: &quot;immersive-space&quot;) {<br>            ImmersiveView()<br>        }<br>    }<br>}</pre><p>Then we declare an immersive space with the according ID.</p><pre>struct ImmersiveView: View {<br>    <br>     @State var entity: Entity?<br><br>     var body: some View {<br>         if let entity {<br>             DraggableEntity(entity: entity)<br>         } else {<br>             ProgressView()<br>                 .progressViewStyle(.circular)<br>                 .controlSize(.large)<br>                 .task {<br>                     do {<br>                         entity = try await Entity(named: &quot;Immersive&quot;,<br>                                                   in: realityKitContentBundle)<br>                     } catch {<br>                         fatalError(&quot;Failed to load Scene&quot;)<br>                     }<br>                 }<br>         }<br>     }<br>}</pre><p>Then ImmersiveView has the same implementation with the DraggableEntity, the only difference is that the we set sofa with a different size and position in Reality composer.</p><p>Let’s run all that !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VyABw5ISX92dz6Gv6f2Ww.png" /></figure><p>Here we go, we have our sofa in the center of the kitchen, not very practical i admit 😅, but while using immersive space, no problem. Now we will be able to move it wherever we want because the space now is all ours.</p><h4>Immersion Styles</h4><p>Let’s explore the concept of immersive space further. Here we talk about “levels of immersion” in VisionOS.</p><p>Note the home button closes the immersion space regardless of the immersion style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*1KyOeSA8NWNQPlcSM0uwrw.png" /></figure><h4>Mixed Style</h4><p>The second level is “mixed,” which is the default when no style is applied. It allows the placement of 3D objects anywhere in the user’s surroundings, or “shared spaces,” while still enabling the user to see their environment.</p><h4>Progressive Style</h4><p>Following is the “Progressive Style,” where, in addition to placing 3D objects, the immersive experience partially conceals the user’s environment. This level immerses the user further, yet they remain connected to their surroundings.</p><blockquote>⚠️ Starting from progressive Immersive we need to ask the user for a permission. We need to be very causious not to overwelm the user.<br>Apple emphasizes a lot on avoiding sudden change in the users environment</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*b0g-USf5DeU4otqvOQMM-Q.png" /></figure><pre>var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }.windowResizability(.contentMinSize)<br>        <br>        ImmersiveSpace(id: &quot;immersive-space&quot;) {<br>            ImmersiveView()<br>        }.immersionStyle(selection: .constant(.progressive), in: .progressive)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzcibRnxngqAOMCVFderIQ.png" /></figure><h4>Full Style</h4><p>The final immersion style is “Full Progressive Style,” where we start talking about virtual reality, where the user is completely immersed in your virtual environment and can no longer see their actual surroundings.</p><pre>@main<br>struct VisionOSDemoApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }.windowResizability(.contentMinSize)<br>        <br>        WindowGroup(id: &quot;volumetric-window&quot;) {<br>            VolumetricWindow()<br>        }<br>        .windowStyle(.volumetric)<br><br>        ImmersiveSpace(id: &quot;immersive-space&quot;) {<br>            ImmersiveView()<br>        }.immersionStyle(selection: .constant(.full), in: .full)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycTKd03qrifMnowlHDEVCw.png" /></figure><blockquote>⚠️ Apple advises giving people control over when they enter or exit fully immersive experiences.<br>⚠️ The system sets a boundary that extends approximately 1.5 meters from the initial position of the person’s head. If their head moves outside of that zone, the system automatically closes the immersicve space.</blockquote><h3>Bonus</h3><h4><strong>SkyBox</strong></h4><p>One must admit that being in the dark with a sofa is not that fun as an immersive experience. So, let’s try making the user’s environment less dark.</p><p>To change the user environment, we can use what is called a Skybox. A Skybox is usually a sphere that has a 360-degree texture image, and when placing the user inside that sphere, it gives them the impression of being in a different environment.</p><p>Let’s go back to sketchfab.com and search for a nice Skybox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MiiK_VVYntoslrZdNpgSQ.png" /></figure><p>Download a skybox of your choice as a USDZ file and go to RealityComposer Pro to create a new scene called Skybox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*wn56ji3STmfsNq-fYcKaVw.png" /></figure><p>Add the skybox USDZ into the project browser and import it to the scene, set its position to (0, 0, 0), and its size to 0.5. We need it big to fully surround the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEvE05Q_hepB6f-1CM4ImA.png" /></figure><p>The last step is to load SkyBox entity and add it to the RealityView.</p><pre>struct ImmersiveView: View {<br>   <br>    @State var entity: Entity?<br>    @State var skybox: Entity?<br><br>    var body: some View {<br>        if let skybox, let entity {<br>            RealityView { content in<br>                content.add(entity)<br>                content.add(skybox)<br>            }<br>        } else {<br>            ProgressView()<br>                .progressViewStyle(.circular)<br>                .controlSize(.large)<br>                .task {<br>                    do {<br>                        entity = try await Entity(named: &quot;Immersive&quot;,<br>                                                  in: realityKitContentBundle)<br>                        skybox = try await Entity(named: &quot;SkyBox&quot;,<br>                                                  in: realityKitContentBundle)<br>                    } catch {<br>                        fatalError(&quot;Failed to load Scene&quot;)<br>                    }<br>                }<br>        }<br>    }<br>}</pre><p>And voilà 🥳, we have our comfy sofa in the middle of a tropical island. I will go grab a cocktail 🍹.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQNWpH3QbadJdj9yrmveQA.png" /></figure><h3>Conclusion</h3><p>It’s undeniable that Apple took a big challenge by releasing such a radically different product, especially since other GAFA companies have already failed in introducing augmented reality into people’s everyday life.</p><p>Mixed reality headset technology faces immense technical and social challenges. What is impressive here is that Apple wants to take this challenge a step further by introducing the concept of spatial computing. And by investing such an amount of money, it’s clear that Apple was preparing for that a few years ago, especially when taking into account the work that has been done in augmented reality frameworks like RealityKit.</p><h4>Privacy</h4><p>One of the biggest concerns that VisionPro raised is privacy: how people would react regarding a device that could be filming them at any moment.</p><p>Apple claims that even though the VisionPro tracks the user’s eyes, developers would not have access to eye-tracking data. However, using the hover event, a VisionOS developer can know if a user has seen a specific object, even without clicking on it.</p><p>Knowing that developers can have access to the user’s hand-tracking data (even if that requires user permission), giving big companies access to such information is just frightening, in my opinion. Social media have now gone very far in retaining attention by studying users behavior through tracking actions.<br>I just can’t imagine what they could do 😱.</p><h4>Would VisionOS be a success for Apple?</h4><p>Apple entered a field where it is in competition with no one. it is in competition with itself, or to be more precise, it is trying to beat human senses. it is trying to beat reality, and that is very, very… very difficult.</p><p>But with VisionPro, Apple achieved considerable milestones. For sure, the technical challenges are huge: how to make the VisionPro lighter, more comfortable, how to expand the battery life, how to avoid having a wire for charging.</p><p>I would not be able to tell if VisionPro would be a revolution like the iPhone was, but I think (and this is my personal opinion) that the real potential resides in the VisionOS operating system.</p><p>Apple has deprecated all its earlier iPhones, but the iOS was the real technological lever. iPhone hardware was not necessarily a revolution, but the iOS was, and I think that this could probably happen for VisionOS.</p><p>It’s extremely difficult to predict if this is going to work for Apple, but I think that keeping an eye on VisionPro would not be a bad idea.</p><p>Thank you very much for reading my article, and have fun with VisionOS development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617b8c9b9f92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Swift: Unit Testing Combine Publisher]]></title>
            <link>https://saad-eloulladi.medium.com/ios-swift-unit-testing-combine-publisher-8a291c7a0067?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a291c7a0067</guid>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 16:09:06 GMT</pubDate>
            <atom:updated>2023-10-22T10:48:37.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvvyZbPwHkER61VsUsxQYQ.jpeg" /></figure><p>iOS development has undergone significant changes since the introduction of SwiftUI and Combine. Reactive programming has become a standard practice, as Combine is included in the iOS SDK by default.</p><p>Unit testing reactive code can sometimes be challenging, as the inputs and outputs are not easily obtained as in the case of imperative programming.</p><h3>The boring approach</h3><p>The most common way to test a Combine publisher is to create an expectation and fulfill it once the value is received, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87499cd3eed00fb865781148dbb8c104/href">https://medium.com/media/87499cd3eed00fb865781148dbb8c104/href</a></iframe><p>While using expectations to test a Combine publisher is intuitive, it comes with some drawbacks:</p><ol><li>It involves writing a lot of code, for what is supposed to be a relatively simple test case.</li><li>When an expected value is not received, having an expectation with a timeout means waiting for the expectation to fail, which can increase the overall execution time of unit tests, potentially leading to longer test durations.</li><li>The use of expectations with timeouts may force us to adjust the timeout value, making the test pass in cases where ideally shouldn’t introduce any unnecessary delays.</li></ol><p>In other words, the above example works, but it’s evident that there’s room for improvement.</p><h3>The alternative</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38bc958607f56ac57034a09a9b961133/href">https://medium.com/media/38bc958607f56ac57034a09a9b961133/href</a></iframe><p>Here, we’re utilizing a different approach, and it’s clear that the test code is significantly simpler and more concise.</p><p>Of course, this is made possible by using a small helper that we’ll discuss in detail below.</p><p>We’ve introduced a spy method for the Combine Publisher, which returns a spy object. Importantly, we don&#39;t retrieve the publisher&#39;s values immediately when subscribing.</p><p>Instead, we use this spy object to capture the values received within the publisher later, after we&#39;ve triggered the actions we want to test.</p><p>With this approach, we effectively separate the asynchronous part from our publisher testing. We no longer need to manage timeouts, except when we explicitly have a delay to handle, which can be managed directly within the test code.</p><p>With this approach, we can easily test error and completion scenarios as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0317b275c6547c90610f38a8b92b7f04/href">https://medium.com/media/0317b275c6547c90610f38a8b92b7f04/href</a></iframe><h3>How it works</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1ab05da7b7e88b3050bf6ad472f2331/href">https://medium.com/media/d1ab05da7b7e88b3050bf6ad472f2331/href</a></iframe><p>We added an extension to the publisher, we introduce a method that takes the subscription as a parameter. This method is responsible for setting up the `sink` and creating the spy object. For each event of the publisher, such as `next`, `finish`, or `error`, we ensure that the spy receives all the relevant data.</p><p>The Publisher Spy is a class that holds properties for values, errors, and completion. Its purpose is to collect data emitted by the publisher and expose them to the test for assertion purposes.</p><blockquote>It’s essential to have the Publisher Spy as a class, rather than a struct, because this allows us to maintain a reference to the spy’s values from outside of the Publisher.</blockquote><h3>Conclusion</h3><p>Writing simple and readable unit tests is crucial for their maintenance and scalability. Using Combine shouldn’t be an obstacle to thoroughly test your code. I hope you find this article useful.</p><p>Take care and keep testing your code 😉 !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a291c7a0067" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Making a modern API client with Async/Await]]></title>
            <link>https://saad-eloulladi.medium.com/swift-making-modern-api-client-with-async-await-8bb091791dbd?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb091791dbd</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Thu, 18 Aug 2022 23:24:02 GMT</pubDate>
            <atom:updated>2022-10-30T20:51:19.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*C9nrKbU2ftx9DpIDndNDgw.jpeg" /></figure><p>Nowadays, most of all popular mobile applications use Rest api to access dynamic data.</p><p>That’s why Apple did a lot of improvement in network layer and concurrency in the recent Swift releases.</p><p>In the following article, we will cover how to create an API client component that allows to call a remote API and parse its result into models using async/await.</p><p>In order for any project to start using async/await, it’s important to implement it in the lower layers, like the network layer or database access.</p><p>In the following example will use a free API called <a href="https://medium.com/www.thecocktaildb.com">thecocktaildb</a>, we will make an API client that searches cocktail by name 🍹.</p><p>Here is an example of a json response we get from search API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f2a69de98eda185133e203b3ac8228/href">https://medium.com/media/49f2a69de98eda185133e203b3ac8228/href</a></iframe><blockquote><strong>iOS version compatibility</strong></blockquote><blockquote>The following example uses async await which is available starting from iOS 13.<br>URLSession async data task is only compatible from iOS 15. <br>If your project is below iOS 15, you can use <strong>withCheckedThrowingContinuation </strong>to convert dataTask closure to async await.<br>You can check the <a href="https://www.swiftbysundell.com/articles/making-async-system-apis-backward-compatible/">following article</a> for further details.</blockquote><h4>ApiError</h4><p>First we will create an enumeration that represents the different errors we might have.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81560f20b542e1d785059e18e4b7a159/href">https://medium.com/media/81560f20b542e1d785059e18e4b7a159/href</a></iframe><h4>BaseApi</h4><p>Then we create the Base api, which allows to send a GET request and return the result as a Result in async way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cc568fc40118a2ef8b2126cfde56219/href">https://medium.com/media/3cc568fc40118a2ef8b2126cfde56219/href</a></iframe><h4>Build Api URL</h4><p>Here we create an URL builder for that provides the a given API url by it’s parameters, here we have also a private constants enum where we declare all API related constants.<br>Note here that if we had different API environments, we could have managed it here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/724e556386162d2c4a07e2cf4686ef7f/href">https://medium.com/media/724e556386162d2c4a07e2cf4686ef7f/href</a></iframe><h4>Models</h4><p>Here we have our models: Bar and Cocktail, which are Codable based structs representing the data we get from our API.<br>Unfortunately here we are obliged to have a Bar model that wraps Cocktail, even if we only need an array of Cocktails.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4a3128e4cfb78303029b9390752032/href">https://medium.com/media/aa4a3128e4cfb78303029b9390752032/href</a></iframe><h4>CocktailApi</h4><p>And finally we have our CocktailApi which is a BaseApi subclass, that returns an async Result type with an array of cocktails.</p><p>BaseApi serves as a generic api that contains the network call implementation, while CocktailApi contains all specific code like the the the service URL. <br>Additionally searchCocktail method maps the result into he wanted type, knowing that usually the returned type is only a wrapper used only for parsing the json.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8c05ed8aee75102172f8144cbe3071e/href">https://medium.com/media/d8c05ed8aee75102172f8144cbe3071e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb091791dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift : Demystifying Swinject (Dependency injection)]]></title>
            <link>https://saad-eloulladi.medium.com/swift-demystifying-swinject-dependency-injection-dd0620c79162?source=rss-d0e5a1b0502c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd0620c79162</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift-ios-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[swinject]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <dc:creator><![CDATA[Saad El Oulladi]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 13:22:38 GMT</pubDate>
            <atom:updated>2020-11-20T16:49:40.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift : Swinject Dependency injection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*1D9tNb2vZ18s4J8uNHxlSg.jpeg" /></figure><p>Sometimes coming across some technical words seems very intimidating. But once you take your time to understand it. You discover that was only a matter of vocabulary . That was the case for me for Swinject, when i got it, i found that i was already doing my self something similar 😂.</p><p>That’s why i decided to try to explain Swinject in the most simple way in this article.</p><h3>Dependency injection</h3><p>⚠️<strong> If you already know what dependency injection is and what is used for. you can skip dependency injection section to the Swinject part.</strong></p><p>Before talking about dependency injection, let’s talk first about not doing dependency injection 😛.</p><p>Not injecting dependencies is considered to be a bad thing (A code smell). Let’s give an example and explain this step by step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9450011d627e873db76860a3a8f6fd00/href">https://medium.com/media/9450011d627e873db76860a3a8f6fd00/href</a></iframe><p>Here we have a simple Cat Model, An Api class that provides cats. and a ViewModel that uses the api.</p><p><strong>ViewModel is using the API, we say that the API is a dependency of ViewModel.</strong></p><p>Here the api is created inside the viewModel, Means that when when doing unit tests, there is no way to use a fake api test with. and this is not good 😊.</p><p>In the case abode we say that the Dependency is not injected.</p><p>Let’s see the next example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7fac8363af112462995721f39f2a81a/href">https://medium.com/media/e7fac8363af112462995721f39f2a81a/href</a></iframe><p>Here instead of initialising the API inside the method, we have an API property we passed through the init.</p><p>Which means during unit tests, we can simply use a fake (Mock) API.</p><h3>Swinject</h3><p>You might be wondering, if dependency injection is possible by passing dependencies in init methods. why do we need a library for that, why do we need Swinject ? 🤔…</p><p>Well in the example above we had only one dependency, which is straightforward, but let’s imagine that we have 5 dependencies. which most likely happens in a real life app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1fdda7b070d3f2cc78511a5b229b113/href">https://medium.com/media/e1fdda7b070d3f2cc78511a5b229b113/href</a></iframe><p>Here we can clearly see that having many dependencies makes the init big and redundant.</p><p>It would also be better to centralise dependencies in only one place instead of having dependencies separated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3fc63f73082d4381b1e5264f1c7c874/href">https://medium.com/media/f3fc63f73082d4381b1e5264f1c7c874/href</a></iframe><p>Now we did the same example using Swinject :</p><ul><li>First, Instead of passing dependencies , we pass a <strong>Container, which is a which is a class that constructs (register) and provides (resolve) dependencies</strong>.</li><li>Then we fetch (resolve) our API dependency from the container using its type.</li><li>Then we init our container.</li><li>And finally we register the Api dependency in container, we tell to the container to return this instance whenever we ask you a dependency of API type.</li></ul><p>Here we can clearly see that injecting dependencies using Swinject, makes code cleaner, and allows instead of passing every single dependency, we only pass Swinject container from which we can get all dependencies we need.</p><h4>Register multiple instances</h4><p>We saw how to register one instance by type, what if we want to register multiple instances of the same type ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ROFQ44Wd70xujl1Kypdcng.jpeg" /></figure><p>Let’s say we have two apis each one with a different path. we can register instances with <strong>type and name</strong> this way :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eda493eee9c6f91c1a114b6aee3b65e2/href">https://medium.com/media/eda493eee9c6f91c1a114b6aee3b65e2/href</a></iframe><p><strong>Register with Arguments</strong></p><p>Sometimes you need to pass an argument with your dependency.<br>This also possible with Swinject.</p><p>let’s take the previous example.We will resolve the API dependency, by giving it the path as an argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a170a192b0ba59970eb5ade0378155e/href">https://medium.com/media/3a170a192b0ba59970eb5ade0378155e/href</a></iframe><h3>Conclusion</h3><p>This is article is not intended to substitute Swinject documentation, the idea here is to explain why you need Dependency Injection, why you may need to use Swinject and what are it’s benefits.</p><p>Since i believe that understanding the main concept is more important that the advanced features, i hope this article has demystified Swinject for you. Thank you for reading 😉</p><h4>Where to Go From Here ?</h4><ul><li><a href="https://www.raywenderlich.com/17-swinject-tutorial-for-ios-getting-started">Swinject Tutorial for iOS: Getting Started</a></li><li><a href="https://github.com/Swinject/Swinject/tree/master/Documentation">Swinject/Swinject</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd0620c79162" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>