<?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 Luiz Fernando Salvaterra on Medium]]></title>
        <description><![CDATA[Stories by Luiz Fernando Salvaterra on Medium]]></description>
        <link>https://medium.com/@luizfernandosalvaterra?source=rss-f55f6d889eeb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RpvOhs9epx4RdUrs3b08Fw.jpeg</url>
            <title>Stories by Luiz Fernando Salvaterra on Medium</title>
            <link>https://medium.com/@luizfernandosalvaterra?source=rss-f55f6d889eeb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:03:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luizfernandosalvaterra/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[Combine Is Not Dead. But You Probably Don’t Need It Anymore]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/combine-is-not-dead-but-you-probably-dont-need-it-anymore-77876a3b8dae?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/77876a3b8dae</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 16:06:25 GMT</pubDate>
            <atom:updated>2026-04-07T16:06:25.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1_gptprAHTiXMrQ9zClbA.png" /></figure><p><em>A practical decision guide for iOS engineers navigating async/await, Observation, and the real remaining use cases for Combine — with code.</em></p><p>There’s a question I’ve been asked a lot lately, usually by developers staring at a Combine pipeline they wrote two years ago with the expression of someone who just found a spider in their keyboard.</p><p>“Should I rewrite all of this?”</p><p>The honest answer is: it depends. But “it depends” is only useful if you know <strong><em>what</em></strong> it depends on — and most of the advice I’ve seen on this topic either waves away Combine entirely (“async/await replaced it, move on”) or defends it unconditionally (“they solve different problems, use both”). Neither of those answers gives you a map. They give you a bumper sticker.</p><p>So let me try to give you the map.</p><p>Combine is not deprecated. Apple hasn’t said anything close to that — there’s no @available(*, deprecated) flag, no migration guide, no official announcement. But “not deprecated” and “actively maintained” are two different things. Combine hasn’t received a meaningful update since WWDC 2021. It has no Swift 6 Sendable conformances. And the two frameworks Apple shipped to replace its core use cases, Swift Concurrency and the Observation framework, were both designed explicitly to remove Combine as a dependency. None of that is deprecation. But it’s also not a vote of confidence.</p><p>In the years since Swift Concurrency landed, something quieter has happened: Combine’s territory has been claimed from two different directions. One you’ve probably heard about. The other one, most developers missed.</p><h4><strong>The problem that never went away</strong></h4><p>To understand where we are, you need to remember where we were.</p><p>Before 2019, writing asynchronous code on iOS was a negotiation with chaos. You had four main tools, none of which talked to each other cleanly.</p><p><strong>Delegation </strong>was the oldest pattern — verbose, boilerplate-heavy, requiring protocol conformance and weak references for every new async interaction. It worked, but composing multiple async sources was painful.</p><p><strong>NotificationCenter</strong> let you broadcast events across your app, but it was string-typed. You passed a Notification.Name and prayed. No compile-time safety, no typed payloads, no error channel.</p><p><strong>Grand Central Dispatch</strong> was powerful but blunt. You got threading control, but you had to wire up every DispatchQueue.main.async by hand. No error propagation. No composability.</p><p>And then there were <strong>completion handlers</strong> — the pattern that took over as the de facto standard in the post-GCD era. They worked until they didn’t.</p><pre>// This is what &quot;async&quot; looked like in 2018.<br>func loadUserProfile(id: String, completion: @escaping (Result&lt;User, Error&gt;) -&gt; Void) {<br>    fetchUser(id: id) { result in<br>        switch result {<br>        case .failure(let error):<br>            completion(.failure(error))<br>        case .success(let user):<br>            self.fetchAvatar(url: user.avatarURL) { avatarResult in<br>                switch avatarResult {<br>                case .failure(let error):<br>                    completion(.failure(error))<br>                case .success(let image):<br>                    self.fetchPosts(userId: user.id) { postsResult in<br>                        switch postsResult {<br>                        case .failure(let error):<br>                            completion(.failure(error))<br>                        case .success(let posts):<br>                            completion(.success(User(user, avatar: image, posts: posts)))<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>I’ll be honest — I don’t miss this. The rightward drift, the duplicated error handling, the invisible control flow. You couldn’t read this code top-to-bottom. You had to trace it like a maze.</p><p>The community’s answer was <strong>RxSwift</strong>, which arrived around 2015. It brought reactive programming to iOS: observable sequences, operators, a composable pipeline model. It was genuinely better. It was also a third-party library, with a steep learning curve, a mental model borrowed from Netflix’s ReactiveX standard, and naming conventions that felt alien to anyone who’d spent years with UIKit.</p><p>Then came WWDC 2019. Apple announced <strong>Combine</strong> alongside SwiftUI — a first-party reactive framework that felt like Apple’s acknowledgment that RxSwift had identified a real problem. Same core idea: publishers, subscribers, operators, pipelines. But native, no dependency, and designed from day one to power SwiftUI’s state model.</p><pre>// The same flow in Combine. More composable — but not without its own costs.<br>func loadUserProfile(id: String) -&gt; AnyPublisher&lt;User, Error&gt; {<br>    fetchUser(id: id)<br>        .flatMap { user in<br>            self.fetchAvatar(url: user.avatarURL)<br>                .map { image in (user, image) }<br>        }<br>        .flatMap { result in<br>            let (user, image) = result<br>            return self.fetchPosts(userId: user.id)<br>                .map { posts in User(user, avatar: image, posts: posts) }<br>        }<br>        .eraseToAnyPublisher()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSGTrPdUTRPo538g-RSQoA.png" /></figure><p>Combine was the right answer for its moment. That moment just didn’t last as long as any of us expected.</p><h4><strong>Combine in production: where things go wrong</strong></h4><p>Here’s the thing about Combine that nobody mentions in the tutorials: it comes with a set of traps that are remarkably easy to fall into, and remarkably hard to debug when you do.</p><p>I’m not saying this to bash Combine. I’m saying it because understanding these traps is the only way to understand why the community shifted so eagerly when async/await appeared.</p><p><strong>Trap 1: The </strong><strong>AnyCancellable that silently kills your subscription.</strong></p><p>When you call sink or assign, Combine returns an AnyCancellable. If you don’t store it somewhere, ARC immediately deallocates it — and AnyCancellable&#39;s deinit calls cancel(). Your subscription dies before it does any work. No warning. No error. Just silence, or worse, a cryptic NSURLErrorDomain Code=-999 that looks like a network failure.</p><pre>// Broken. The subscription lives for exactly zero seconds.<br>func loadData() {<br>    URLSession.shared.dataTaskPublisher(for: url)<br>        .map(\.data)<br>        .sink(receiveCompletion: { _ in },<br>              receiveValue: { data in<br>                  print(data) // Never called.<br>              })<br>    // AnyCancellable is discarded here. ARC destroys it. Done.<br>}<br><br>// Fixed. Store it.<br>var cancellable: AnyCancellable?<br><br>func loadData() {<br>    cancellable = URLSession.shared.dataTaskPublisher(for: url)<br>        .map(\.data)<br>        .sink(receiveCompletion: { _ in },<br>              receiveValue: { data in print(data) })<br>}</pre><p>This is the single most-reported beginner trap in Combine. The compiler doesn’t warn you. It just doesn’t work.</p><p><strong>Trap 2: An error permanently kills the entire pipeline.</strong></p><p>In Combine, an unhandled error doesn’t throw. It terminates. The whole subscription is done. Finished. Whatever events come after — they’ll never reach your subscriber.</p><pre>// searchTerm: a publisher of text field values, e.g. $searchField.publisher<br><br>// Broken. After the first network error, this search bar is dead forever.<br>searchTerm<br>    .flatMap { term in<br>        URLSession.shared.dataTaskPublisher(for: searchURL(term))<br>    }<br>    .sink(<br>        receiveCompletion: { completion in<br>            // Once this fires with .failure, nothing else ever arrives.<br>        },<br>        receiveValue: { data in /* ... */ }<br>    )<br>    .store(in: &amp;cancellables)<br><br>// Fixed. Handle errors inside flatMap so the outer pipeline survives.<br>searchTerm<br>    .flatMap { term in<br>        URLSession.shared.dataTaskPublisher(for: searchURL(term))<br>            .map(\.data)<br>            .replaceError(with: Data()) // Error absorbed here. Pipeline lives.<br>    }<br>    .sink { data in /* ... */ }<br>    .store(in: &amp;cancellables)</pre><p>I’ve seen this ship to production. A search bar that works perfectly until the first API error, and then silently stops responding forever. The model is mathematically correct for event streams — a stream that fails <strong><em>has</em></strong> ended. But it contradicts every instinct you built from imperative error handling.</p><p><strong>Trap 3: </strong><strong>assign(to:on:) always creates a retain cycle.</strong></p><p>assign(to:on:) holds a strong reference to whatever object you pass as on:. If that object is self, and self holds the AnyCancellable, you have a classic retain cycle. Neither deallocates. There’s no way to make assign(to:on:) capture weakly — it doesn’t support it.</p><pre>// namePublisher: AnyPublisher&lt;String, Never&gt;<br><br>// Retain cycle. ViewModel never deallocates.<br>class ViewModel: ObservableObject {<br>    @Published var name = &quot;&quot;<br>    var cancellable: AnyCancellable?<br><br>    func setup() {<br>        cancellable = namePublisher<br>            .assign(to: \.name, on: self) // Strong ref to self. Cycle.<br>    }<br>}<br><br>// Fixed option 1: sink with [weak self]<br>cancellable = namePublisher<br>    .sink { [weak self] value in self?.name = value }<br><br>// Fixed option 2: assign to @Published directly (iOS 14+, no AnyCancellable needed)<br>namePublisher.assign(to: &amp;$name)</pre><p><strong>Trap 4: </strong><strong>@Published fires in </strong><strong>willSet, not </strong><strong>didSet.</strong></p><p>Every other observer pattern in iOS — KVO, didSet, NotificationCenter— fires <strong><em>after</em></strong> the value changes. @Published fires <strong><em>before</em></strong>. Which means if you read the property inside a sink closure, you get the old value, not the new one.</p><pre>class ViewModel: ObservableObject {<br>    @Published var count = 0<br>    var cancellable: AnyCancellable?<br><br>    init() {<br>        cancellable = $count.sink { newValue in<br>            print(&quot;Received:&quot;, newValue)   // Correct new value<br>            print(&quot;Property:&quot;, self.count) // WRONG — still the old value<br>        }<br>    }<br>}</pre><p>This one generated 65+ replies on Swift Forums asking if it’s a bug. It’s not — it’s by design, because SwiftUI needs the pre-change notification to do its diffing. But it bites developers who rely on the property value inside a side effect.</p><p><strong>Trap 5: Combine + Swift 6 = Sendable errors everywhere.</strong></p><p>This is the most recent and arguably the most consequential. Swift 6’s strict concurrency checking treats Combine’s internal types as non-Sendable — because they aren’t. Apple has not updated Combine for Swift 6 compatibility. Not at WWDC 2022. Not 2023. Not 2024. Not 2025.</p><p>If you’re migrating a Combine-heavy codebase to Swift 6, you’re in for a challenging time. There’s no automated path. The community on Swift Forums has been explicit about this: <a href="https://forums.swift.org/t/combine-and-the-road-to-swift-6/65396">Combine and the road to Swift 6</a>.</p><p>None of this makes Combine bad. These are real traps, but they’re learnable. What they tell you is that Combine’s cost — in cognitive overhead, in debugging friction, in migration risk — is substantial. That cost needs to be justified by what you’re getting in return. Which brings us to why the ecosystem shifted.</p><h4><strong>What Apple actually replaced Combine with (hint: it’s two things)</strong></h4><p>Here’s the framing I wish I’d had two years ago: Combine was doing two distinct jobs in most iOS codebases. Apple replaced those two jobs with two different tools. If you only know about one of them, the picture is incomplete.</p><p>The first job was concurrency. Fetching data from APIs, chaining async operations, handling background work and delivering results to the main thread. Combine was used for this because it was the most composable tool available in 2019–2020.</p><p>The second job was state. ObservableObject + @Published + @ObservedObject / @StateObject / @EnvironmentObject. The entire state layer of SwiftUI for iOS 13–16 runs on Combine.</p><p>Swift Concurrency — async/await, AsyncSequence, structured concurrency — took over the first job.</p><p>The @Observable macro (iOS 17, <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0395-observability.md">SE-0395</a>) took over the second.</p><p>Two things replaced two different parts of Combine at the same time. That’s why it feels squeezed from both sides.</p><p>Now — here’s the part that surprises most developers. To understand why the state replacement runs so deep, you need to know what was actually hiding under the hood of your SwiftUI ViewModels.</p><p>Take a completely ordinary ViewModel:</p><pre>import SwiftUI<br><br>// This looks like a SwiftUI pattern.<br>// It is actually a Combine pattern.<br>class ProfileViewModel: ObservableObject {<br>    @Published var username = &quot;&quot;<br>    @Published var posts: [Post] = []<br>}</pre><p>ObservableObject is not a SwiftUI type. It’s documented under the <strong>Combine</strong> framework <a href="https://developer.apple.com/documentation/combine/observableobject">here</a>.</p><p>@Published is not a SwiftUI property wrapper. <a href="https://developer.apple.com/documentation/combine/published">It’s a <strong>Combine</strong> property wrapper</a></p><p>The reason you don’t need to write import Combine in a SwiftUI file is that SwiftUI re-exports these types for you. They feel native to SwiftUI. But the dependency is there, under the hood. If you’ve ever used ObservableObject in a UIKit target or a pure model layer without import SwiftUI, you discovered import Combine immediately.</p><p>And objectWillChange — the publisher that drives SwiftUI’s reactivity for ObservableObject — is of type ObservableObjectPublisher, a dedicated final class in Combine with Output = Void, Failure = Never. This matters because when @Observable removes it, it’s not just changing a pattern. It’s removing a concrete Combine type from the equation entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sqK0Y1U0lzmnZCjqdvhww.png" /></figure><p>The SE-0395 proposal is unusually direct about this. Among the listed limitations of ObservableObject that motivated the new system: <em>”require using Combine, which is restricted to Darwin platforms and does not use current Swift concurrency features.”</em> That’s Apple’s written acknowledgment that Combine was a platform constraint, not just a design choice.</p><p>The @Observable macro uses ObservationRegistrar internally — no Combine involved. It works on Linux and Windows. That portability would be impossible if it depended on Combine, which is Darwin-only.</p><pre>// Before (iOS 13-16): Combine is the backbone.<br>import SwiftUI // re-exports Combine types<br><br>class ProfileViewModel: ObservableObject {<br>    @Published var username = &quot;&quot;   // Combine.Published<br>    @Published var posts: [Post] = [] // Combine.Published<br>    // objectWillChange: Combine.ObservableObjectPublisher synthesized automatically<br>}<br><br>// After (iOS 17+): No Combine. No @Published. No objectWillChange.<br>import SwiftUI<br>import Observation<br><br>@Observable<br>class ProfileViewModel {<br>    var username = &quot;&quot;   // Plain stored property. Observation tracks it automatically.<br>    var posts: [Post] = []<br>}</pre><p>And on the concurrency side, async/await (<a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0296-async-await.md">SE-0296</a>), Swift 5.5 / iOS 15 eliminated the primary reason most developers reached for Combine in the first place:</p><pre>// Before: Combine for a network call.<br>func fetchUser(id: String) -&gt; AnyPublisher&lt;User, Error&gt; {<br>    URLSession.shared.dataTaskPublisher(for: userURL(id))<br>        .map(\.data)<br>        .decode(type: User.self, decoder: JSONDecoder())<br>        .receive(on: DispatchQueue.main)<br>        .eraseToAnyPublisher()<br>}<br>// Caller needs to sink, manage AnyCancellable, store it somewhere.<br><br>// After: async/await for the same thing.<br>func fetchUser(id: String) async throws -&gt; User {<br>    let (data, _) = try await URLSession.shared.data(from: userURL(id))<br>    return try JSONDecoder().decode(User.self, from: data)<br>}<br>// Caller just awaits. Cancellation is structured. No AnyCancellable.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPGpOu1n5prO2h1QabEm-w.png" /></figure><h4><strong>Where async/await wins — and where it falls short</strong></h4><p>For most of what iOS developers do every day, async/await is simply better. I’ll say it plainly because I think the hedging around this topic has gone on long enough.</p><p>Network calls are clearer. Sequential async work is readable top-to-bottom like synchronous code. You get structured cancellation via Task without managing any subscription lifetime. @MainActor replaces .receive(on:DispatchQueue.main) — and it’s enforced at compile time, not something you need to remember to add. There are no retain cycles from forgetting [weak self] in a sink. There’s no willSet timing surprise.</p><pre>// async/await: clear, linear, no ceremony.<br>@MainActor<br>func loadProfile() async {<br>    do {<br>        let user = try await fetchUser(id: currentUserId)<br>        let posts = try await fetchPosts(userId: user.id)<br>        self.user = user<br>        self.posts = posts<br>    } catch {<br>        self.errorMessage = error.localizedDescription<br>    }<br>}<br><br>// The Task-based call site, with automatic cancellation when the view disappears:<br>.task {<br>    await viewModel.loadProfile()<br>}</pre><p>But async/await has real gaps. I’d be doing you a disservice to skip them.</p><p><strong>Gap 1: No native multicast.</strong> AsyncStream and AsyncSequence are single-consumer abstractions. If you try to iterate the same stream from two places concurrently, the values don’t get broadcast — they get consumed by whichever consumer reads first. The second consumer gets whatever’s left.</p><pre>let stream = AsyncStream&lt;User&gt; { continuation in<br>    // ... produces user updates<br>}<br><br>// Consumer A<br>Task { for await user in stream { profileView.update(with: user) } }<br><br>// Consumer B — does NOT get independent copies of the same events.<br>// It races with Consumer A for the same values.<br>Task { for await user in stream { analyticsService.track(user) } }</pre><p>This is a fundamental architectural limitation, not a missing feature you can work around easily.</p><p><strong>Gap 2: No </strong><strong>CurrentValueSuject equivalent.</strong> Combine’s CurrentValueSubject gives you a stream that replays its current value to new subscribers. There’s no direct equivalent in the structured concurrency world. You can approximate it with AsyncChannel from Swift Async Algorithms, but it’s not an exact match.</p><p><strong>Gap 3: Operators came later.</strong> Initially, async/await had no debounce, no throttle, no combineLatest. Apple announced <a href="https://github.com/apple/swift-async-algorithmshttps://github.com/apple/swift-async-algorithms">Swift Async Algorithms</a> in March 2022 as an open-source package to fill this gap (reaching 1.0 in December 2023). It’s excellent — but it’s a separate dependency you need to add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFYJKLZ_CMSsotafcmCTaA.png" /></figure><h4><strong>Where Combine still wins</strong></h4><p>I want to be specific here, because this is where the conversation usually turns vague. Saying “Combine still has its uses” without naming them isn’t advice — it’s a dodge.</p><p><strong>Multicast / broadcast.</strong> This is Combine’s clearest remaining advantage. When you need one publisher feeding multiple independent subscribers — an event bus, a shared data stream, multiple UI components reacting to the same source — Combine handles this cleanly. PassthroughSubject and CurrentValueSubject are multicast by design.</p><pre>// One subject, multiple independent subscribers. Each gets every event.<br>let userUpdates = PassthroughSubject&lt;User, Never&gt;()<br><br>userUpdates<br>    .sink { user in profileView.update(with: user) }<br>    .store(in: &amp;cancellables)<br><br>userUpdates<br>    .sink { user in analyticsService.track(user) }<br>    .store(in: &amp;cancellables)<br><br>userUpdates<br>    .map(\.notificationCount)<br>    .filter { $0 &gt; 0 }<br>    .sink { count in badgeService.update(count: count) }<br>    .store(in: &amp;cancellables)<br><br>// Sending one event reaches all three subscribers independently.<br>userUpdates.send(updatedUser)</pre><p>Trying to replicate this with a raw AsyncStream doesn’t work the same way. The stream has one sequence of values, and if you’re iterating it from three different places concurrently, you’re in trouble. AsyncChannel from Swift Async Algorithms gets closer but behaves differently — it doesn’t replay current values and doesn’t have the same multicast semantics as a Subject.</p><p><strong>Complex event pipelines.</strong> When you have a genuinely complex pipeline — multiple operators chained, filtering and transforming and combining streams — Combine’s declarative syntax is genuinely elegant. A search bar with debounce, deduplication, cancellation of in-flight requests, and switching to the latest:</p><pre>// searchText is a @Published var updated from a SwiftUI TextField binding or UITextField delegate<br>$searchText<br>    .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)<br>    .removeDuplicates()<br>    .flatMap(maxPublishers: .max(1)) { term in  // cancels previous in-flight request<br>        self.searchService.search(term: term)<br>            .replaceError(with: [])<br>    }<br>    .assign(to: &amp;$searchResults)</pre><p>This is readable in a way that an equivalent implementation with structured concurrency tasks and cancellation tokens wouldn’t quite match.</p><p><strong>iOS 15/16 minimum targets.</strong> If you can’t yet require iOS 17, @Observable isn’t available. Your SwiftUI state layer still runs on ObservableObject + @Published. That is Combine. There’s no way around it, and there’s no reason to fight it.</p><p><strong>Existing codebases.</strong> If you have 50,000 lines of working Combine code and your app is stable, there’s no engineering argument for rewriting it just to replace the framework. Rewrite when you’re changing behavior, not just because something newer exists.</p><h4><strong>Making them work together</strong></h4><p>Real-world codebases don’t get to start fresh. If you have Combine on one side and async/await on the other, the two can coexist cleanly — you just need to know the bridges.</p><p><strong>From Combine to async/await: </strong><strong>publisher.values</strong></p><p>Apple added .values to publishers in WWDC 2021. It turns any Combine publisher into an AsyncSequence, letting you iterate it with for await in.</p><pre>// Bridge: consume a Combine publisher with async/await.<br>// Task is cancellable just like AnyCancellable — call task.cancel() to stop it.<br>let task = Task {<br>    for await user in userPublisher.values {<br>        await updateUI(with: user)<br>    }<br>}</pre><p><strong>From async/await to Combine: </strong><strong>Future</strong></p><p>If you need to bring an async function into a Combine pipeline, wrap it in a Future.</p><pre>// Bridge: wrap an async function as a Combine publisher.<br>func fetchUserPublisher(id: String) -&gt; AnyPublisher&lt;User, Error&gt; {<br>    Future { promise in<br>        Task {<br>            do {<br>                let user = try await fetchUser(id: id)<br>                promise(.success(user))<br>            } catch {<br>                promise(.failure(error))<br>            }<br>        }<br>    }<br>    .eraseToAnyPublisher()<br>}</pre><p><strong>Bonus: Bridging callback-based code into async/await</strong></p><p>This one isn’t specifically about Combine, but it comes up during any migration. withCheckedContinuation brings any completion-handler API into the async/await world:</p><pre>// Bridge: callback-based API → async/await.<br>// Assumes legacyService.fetch(id:completion:) calls back with Result&lt;Data, Error&gt;.<br>func legacyFetch(id: String) async throws -&gt; Data {<br>    try await withCheckedThrowingContinuation { continuation in<br>        legacyService.fetch(id: id) { result in<br>            continuation.resume(with: result)<br>        }<br>    }<br>}</pre><p>The pattern that works well in practice: async/await for the data layer, @Observable (or ObservableObject if pre-iOS 17) for the view layer, and bridging at the boundary with .values or Task. You don’t have to commit to one world. Use the bridges.</p><h4><strong>The decision framework: what to use when</strong></h4><p>Here’s what I actually think you should do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEPsMxBh3Pdo3F8DlxK7DQ.png" /></figure><p>For a new project on iOS 17+, the defaults are clear: async/await for all concurrency, @Observable for all SwiftUI state. Drop @Published, drop @ObservedObject, drop @StateObject. Reach for Combine only if you specifically need multicast streams or a complex event pipeline. And if you do, you’ll know it — those use cases have a shape.</p><p>For an existing codebase with a lower deployment target, your state layer is still built on ObservableObject, and that’s fine. Start migrating network calls and async operations to async/await — that’s where you’ll get the clearest return: no AnyCancellable lifetime management, better readability, and a head start on Swift 6 compatibility. Hold off on migrating state to @Observable until your minimum target allows it. When it does, migrate view by view, not all at once.</p><p>On Swift 6: Combine has no Sendable conformances and won’t get them. If you’re migrating a Combine-heavy codebase to Swift 6, plan time for this. async/await and @Observable work with strict checking natively.</p><p>One more signal worth noting: Apple’s own Xcode coding agent now includes an explicit instruction in its system prompt — “<em>Avoid using the Combine framework and instead prefer to use Swift’s async and await versions of APIs instead.”</em> This isn’t a deprecation notice. Apple hasn’t made any official announcement. But it tells you something about institutional direction when Apple’s own tooling is being told not to generate Combine code.</p><h4><strong>Conclusion</strong></h4><p>I started writing iOS apps when completion handlers were modern. I remember the first time I saw RxSwift and thought it was either brilliant or insane — I still haven’t fully resolved that. I remember the relief of writing Combine pipelines that were actually readable compared to nested closures, and then the frustration of chasing down a silent AnyCancellable bug for three hours.</p><p>And I remember the first time I replaced a full Combine data pipeline with three lines of async/await and thought: <em>oh. this is what it was supposed to feel like.</em></p><p>That’s the arc. None of these tools were wrong. They were answers to the problems their moment created.</p><p>Knowing which territory belongs to which tool is not a matter of preference — it’s a matter of using the right level of complexity for the problem you actually have. That’s the map.</p><p>If you’re ready to start migrating, pick the move with the best return first: replace Combine network calls with async/await. Lowest risk, most immediate payoff.</p><p>When your minimum target allows it, start moving ObservableObject ViewModels to @Observable. If you need debounce or throttle in the async/await world, the <a href="https://github.com/apple/swift-async-algorithms">Swift Async Algorithms</a> package is worth adding.</p><p>Combine isn’t dead. It just stopped being the answer to most of the questions you’re asking.</p><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77876a3b8dae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sendable in Swift: What Nobody Tells You Until You Hit Production]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/sendable-in-swift-what-nobody-tells-you-until-you-hit-production-2d682b0689db?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d682b0689db</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 12:13:50 GMT</pubDate>
            <atom:updated>2026-03-23T12:14:15.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZWOXFMUmhfNQkyYOscuaA.png" /></figure><p><em>How Swift’s Sendable protocol prevents data races at the type level — and what happens when you try to cheat it.</em></p><h4>Introduction</h4><p>You enabled Swift 6 strict concurrency. Maybe a colleague enabled it for you. Either way, you opened Xcode and found forty-something warnings you didn’t have yesterday.</p><p>All of them say some variation of the same thing: <em>Sending value of non-sendable type across actor boundaries.</em></p><p>You Google it. The first result tells you to add @unchecked Sendable. You do. The warnings go away. You move on.</p><p>I’ve been there. And for a while, I thought that was the answer. Silence the compiler, ship the feature.</p><p>It wasn’t until I hit a subtle, hard-to-reproduce data race in production — one that the compiler had been trying to warn me about all along — that I stopped treating Sendable as noise and started treating it as information.</p><p>Let’s start with what that warning is actually telling you, and why ignoring it cost me a production incident.</p><h4>The Compiler Complained. Now What?</h4><p>Here’s the scenario that probably brought you here. You have a class — maybe a view model, a cache, a service object — and you’re passing it across an actor boundary:</p><pre>class UserSession {<br>    var currentUser: User?<br>    var authToken: String?<br>}<br><br>actor SessionManager {<br>    func update(with session: UserSession) {<br>        // do something with session<br>    }<br>}<br><br>let session = UserSession()<br>let sessionManager = SessionManager()<br><br>Task {<br>    await sessionManager.update(with: session)<br>    // ⚠️ Sending value of non-sendable type &#39;UserSession&#39;<br>    //    risks causing data races<br>}</pre><p>That warning deserves a closer read. It’s not saying your code <strong>will</strong> crash. It’s not saying there’s a bug right now. It’s saying: <em>if this value is accessed from another context while you’re sending it here, the outcome is undefined</em>. The compiler found a potential data race and flagged it, before it ever ran.</p><p>The instinct to add @unchecked Sendable to UserSession and move on is understandable. But before we do that, let’s talk about why this warning exists at all, because the reason is more interesting than the fix.</p><h4>Before Sendable: The Data Race We Didn’t See</h4><p>Before Swift Concurrency arrived in Swift 5.5, thread safety was entirely manual. You created DispatchQueue&#39;s, sprinkled NSLock calls around shared state, and hoped you got every access site. The compiler didn’t know or care about any of it.</p><p>Here’s what that looked like in practice:</p><pre>// Pre-concurrency: &quot;safe&quot; counter using GCD<br>class Counter {<br>    private var value = 0<br>    private let queue = DispatchQueue(label: &quot;counter.queue&quot;)<br><br>    func increment() {<br>        queue.async {<br>            self.value += 1 // manually serialized... right?<br>        }<br>    }<br><br>    func get() -&gt; Int {<br>        return value // oops — no queue here. silent data race.<br>    }<br>}</pre><p>That get() function reads value from whatever thread calls it, while increment() modifies it on a background queue. Both can run at the same time. The compiler compiles it happily, ships it happily, and the app runs mostly fine — until it doesn’t. Data races are notoriously non-deterministic. You might go months without seeing one in production, then hit it under load on a Tuesday.</p><p>The problem wasn’t that developers were careless. It’s that the tools didn’t help. Thread safety was a convention, not a contract. If you forgot a lock, or forgot to use the queue in one method, nothing stopped you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8O00RUGxadzuoSKR3Idi0Q.png" /></figure><p>This is exactly the problem Sendable was built to solve, not at runtime but at compile time. If the compiler knows which values are safe to transfer across concurrency boundaries, it can reject the unsafe ones before your code ever runs. Thread safety stops being something you remember and becomes something the language enforces.</p><p>Swift 5.5 didn’t just add async/await. It shipped a whole concurrency model: structured tasks, actors, and sendables, all at once, all designed to work together. Sendable is the piece that closes the gap the compiler couldn’t reach before.</p><h4>What Sendable Actually Is</h4><p>Here’s something that surprised me when I first read <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0302-concurrent-value-and-concurrent-closures.md">SE-0302</a>, the proposal that introduced Sendable: the protocol has no requirements.</p><pre>public protocol Sendable { }</pre><p>That’s it. No methods to implement, no properties to declare. It’s called a marker protocol — its only purpose is to act as a compile-time signal. Conforming to Sendable is a promise you’re making to the compiler: <em>this value is safe to transfer across concurrency boundaries.</em></p><p>No runtime cost. No generated code. Just a contract.</p><p>A value is Sendable if sharing it across concurrent contexts can’t produce data races. Immutable values are inherently safe. Value types that copy on assignment are safe if their contents are safe. Actors are safe because they serialize all access to their state.</p><p>The rules differ depending on what kind of type you have:</p><pre>// 1. Structs with all-Sendable properties conform implicitly<br>struct Message {<br>  let id: UUID // Sendable<br>  let text: String // Sendable<br>  // ✅ Message implicitly conforms to Sendable - no annotation needed<br>}<br><br>// 2. Final classes can conform explicitly if all stored properties are<br>// immutable and Sendable<br>final class Configuration: Sendable {<br>  let apiURL: URL // Sendable<br>  let timeout: TimeInterval // Sendable<br>  // ✅ Compiler is happy - immutable + final = no subclasses can break this<br>}<br><br>// 3. Mutable classes can&#39;t conform - the compiler won&#39;t allow it<br>class UserSession: Sendable { // ❌ Stored property &#39;currentUser&#39; of &#39;Sendable&#39;-conforming<br>  var currentUser: User? // class &#39;UserSession&#39; is mutable<br>  var authToken: String?<br>}</pre><p>That third case is the one you hit in production. A mutable class can’t be Sendable because nothing stops two concurrent contexts from modifying it at the same time. The compiler isn’t being strict for fun — it’s pointing to a genuine design problem. In practice, this is where most migration pain comes from: you have a class that’s been passed around freely for years, and Swift 6 is the first thing that asks whether that was ever actually safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5J9kv6kHQ5ob0akSkZZgg.png" /></figure><h4>The Public API Trap</h4><p>Here’s something that tripped me up the first time I wrote a Swift package with strict concurrency enabled. I had a clean internal struct, all immutable, all Sendable properties, and it was implicitly conforming just fine. Then I made it public.</p><p>The warnings came back.</p><pre>// Internal: implicitly Sendable ✅<br>struct UserPreferences {<br>  let theme: String<br>  let language: String<br>}<br><br>// Public: NO implicit conformance ⚠️<br>public struct UserPreferences {<br>  let theme: String<br>  let language: String<br>  // Public non-frozen structs do NOT auto-conform to Sendable<br>}</pre><p>At first this felt like a bug or an arbitrary restriction. It’s actually a deliberate design decision, and once you see the reasoning it makes complete sense.</p><p>Imagine you ship a public library. Your UserPreferences struct auto-conforms to Sendable because today all its properties are Sendable. Consumers of your library start passing it across actor boundaries everywhere. Six months later, you add a cache:</p><pre>public struct UserPreferences {<br>  let theme: String<br>  let language: String<br>  var cache: NSCache&lt;NSString, AnyObject&gt; // NSCache is NOT Sendable<br>}</pre><p>NSCache isn’t Sendable. The moment you add it, your struct can no longer conform, and every consumer who was depending on that implicit conformance gets a compilation error. You’ve made a breaking change to your API without touching any public interface. In a real SDK with external consumers, that’s the kind of thing that breaks someone’s CI on a Friday.</p><p>Apple’s solution: public non-frozen types never get implicit Sendable conformance. You have to opt in explicitly, which means you’re making a conscious API commitment.</p><pre>// Explicit conformance: you&#39;re committing to this<br>public struct UserPreferences: Sendable {<br>  let theme: String<br>  let language: String<br>}</pre><p>For cases where you’re adopting Swift 6 in an existing codebase and can’t immediately audit all your public types, @preconcurrency works as a bridge:</p><pre>// Tells the compiler: &quot;this existed before strict concurrency,<br>// don&#39;t flag call sites that pass it across boundaries&quot;<br>@preconcurrency public struct UserPreferences {<br>  let theme: String<br>  let language: String<br>}</pre><p>You’ll also see it at the import level (@preconcurrency import SomeModule), which suppresses Sendable warnings for types from a module that hasn’t adopted strict concurrency yet. Migration tool, not a permanent solution. But it buys you time to do the audit properly.</p><h4>@unchecked Sendable: The Escape Hatch You Should Fear</h4><p>Let’s go back to that original UserSession class. You’ve read the above, you understand why it can’t be Sendable, and now you’re wondering how to actually fix it.</p><p>One option the compiler offers is @unchecked Sendable. And here’s where I want to be direct: use this carefully and rarely.</p><p>What it does is simple: it tells the compiler “I know this type doesn’t meet the automatic requirements, but I’m guaranteeing it’s safe — trust me.” The compiler steps back, disables all related checks, and suppresses downstream warnings.</p><p>There are legitimate uses. If you’re wrapping a class that uses NSLock internally to serialize access, the compiler can’t see that — but you can:</p><pre>// Legitimate use: the class IS thread-safe, but the compiler can&#39;t verify it<br>final class ThreadSafeCache: @unchecked Sendable {<br>    private var storage: [String: Any] = [:]<br>    private let lock = NSLock()<br><br>    func set(_ value: Any, for key: String) {<br>        lock.lock()<br>        defer { lock.unlock() }<br>        storage[key] = value<br>    }<br><br>    func value(for key: String) -&gt; Any? {<br>        lock.lock()<br>        defer { lock.unlock() }<br>        return storage[key]<br>    }<br>}</pre><p>The lock makes this genuinely thread-safe. The compiler just can’t prove it. @unchecked is the right call here, but only because you’ve done the work.</p><p>Now here’s the dangerous version:</p><pre>// Dangerous: @unchecked hides a real data race<br>final class UserSession: @unchecked Sendable {<br>    var currentUser: User?    // mutable, unprotected<br>    var authToken: String?    // mutable, unprotected<br>}<br><br>let session = UserSession()<br>let sessionManager = SessionManager()<br><br>actor SessionManager {<br>    func update(with session: UserSession) async {<br>        session.currentUser = User(name: &quot;Alice&quot;) // Task A<br>    }<br>}<br><br>// Meanwhile, somewhere else:<br>Task {<br>    session.currentUser = User(name: &quot;Bob&quot;) // Task B<br>}<br>// Task A and Task B run concurrently. currentUser&#39;s final value is undefined.<br>// The compiler no longer warns you. The data race is invisible again.</pre><p>This is exactly the pre-Sendable world, except now it’s self-inflicted.</p><p>@unchecked Sendable doesn’t make your code thread-safe. It makes your code <em>look</em> thread-safe to the compiler. The responsibility transfers entirely to you, and unlike the compiler, you can get distracted, forget details, or make mistakes six months later when you add a new mutable property and forget the implication.</p><p>A rule I follow: before writing @unchecked Sendable, write a comment that explains exactly what mechanism ensures thread safety. If you can’t write that comment, you’re not ready to use the annotation.</p><p>There’s also a subtler danger worth knowing: cascading suppression. One @unchecked can silence warnings that were pointing to a second, unrelated problem. You think you fixed one thing; actually you hid two.</p><p>For UserDefaults, this comes up often. Apple’s docs say it’s thread-safe, but it’s not marked Sendable because UserDefaults is an open class, meaning Apple’s own internal code creates subclasses, and those subclasses might not be thread-safe. The conservative choice is to leave it unmarked. If you need it in a concurrent context, create a new instance per context or wrap it in a dedicated actor.</p><h4>Gotchas That’ll Bite You in Production</h4><p>A few specific patterns produce Sendable warnings in ways that genuinely caught me off guard. Worth knowing before you run into them at 11pm with a deadline.</p><p><strong>Property wrappers create a hidden mutable variable</strong></p><p>Property wrappers secretly synthesize a backing storage variable — and that backing variable is mutable by default. You don’t see it in your code, but the compiler does.</p><pre>@propertyWrapper<br>struct Wrapper&lt;T&gt; {<br>    var wrappedValue: T // this becomes a mutable `var _property` on the class<br>}<br><br>// ❌ The synthesized `_volume` backing var is mutable — breaks Sendable<br>final class AudioPlayer: Sendable {<br>    @Wrapper var volume: Int = 50<br>}<br><br>// ✅ Workaround: isolate to MainActor instead<br>@MainActor<br>final class AudioPlayer {<br>    @Wrapper var volume: Int = 50<br>}</pre><p>@MainActor isolates the class to the main thread, which serializes all access. The mutable backing variable is no longer a problem because only one thread ever touches it.</p><p><strong>weak var is rejected in </strong><strong>Sendable classes</strong></p><p>The delegate and observer patterns rely on weak references. But weak var is mutable — it can be set to nil as the referenced object deallocates — and mutable stored properties in Sendable classes are rejected by the compiler.</p><pre>// ❌ &#39;weak&#39; variable &#39;delegate&#39; is not allowed in a &#39;Sendable&#39; class<br>final class DataLoader: Sendable {<br>    weak var delegate: DataLoaderDelegate?<br>}<br><br>// ✅ Option 1: Use an actor to serialize access<br>actor DataLoader {<br>    weak var delegate: DataLoaderDelegate?<br>}<br><br>// ✅ Option 2: Pass delegate through method calls instead of storing it<br>final class DataLoader: Sendable {<br>    func load(notifying delegate: DataLoaderDelegate) async {<br>        // delegate used locally, not stored<br>    }<br>}</pre><p>This one often requires rethinking the design slightly. The actor option is usually the cleanest path.</p><p><strong>Copy-on-write types with shared backing storage</strong></p><p>Swift’s built-in collections (Array, Dictionary, Set) are value types with copy-on-write semantics, and they’re all Sendable. Build your own CoW type, though, and the compiler sees the shared reference and gets nervous:</p><pre>// A reference type used as backing storage<br>class Storage {<br>    var items: [String] = []<br>}<br><br>// ❌ Stored property &#39;_storage&#39; of &#39;Sendable&#39;-conforming struct<br>//    &#39;Buffer&#39; has non-sendable type &#39;Storage&#39;<br>struct Buffer: Sendable {<br>    private var _storage: Storage // reference type, shared before copy<br>}<br><br>// ✅ Use @unchecked with a clear comment explaining the safety guarantee<br>struct Buffer: @unchecked Sendable {<br>    private var _storage: Storage<br>    // Safety: _storage is copied before any mutation (CoW).<br>    // Concurrent reads on separate copies are safe; no shared mutable state.<br>}</pre><p>This is one of the few cases where @unchecked is reasonable, but only if you’ve actually implemented proper CoW semantics with isKnownUniquelyReferenced. That’s Swift’s built-in function for checking whether a reference type has a single owner: if it does, you hold the only copy and can mutate it safely without affecting anyone else.</p><p><strong>A Contract, Not a Complaint</strong></p><p>Before Swift Concurrency, I had data races I didn’t know about. Code that worked fine in testing, worked fine in development, and then quietly misbehaved under production load in ways that were nearly impossible to reproduce. The compiler had nothing to say about it.</p><p>Sendable made the invisible visible.</p><p>The friction you feel when adopting strict concurrency is real. The warnings are sometimes excessive, the gotchas around property wrappers and weak references are genuinely annoying, and @unchecked is always tempting when you’re busy. But that friction is pointing at something — a design decision you haven’t thought through yet, a type that’s doing too much, a pattern that assumed single-threaded access without saying so.</p><p>That’s not the compiler being annoying. That’s the compiler doing its job.</p><p>If you want somewhere concrete to start: set SWIFT_STRICT_CONCURRENCY = complete in your build settings and sit with the warnings for a bit before reaching for @unchecked. Most of them are pointing at something real. Then go audit your existing @unchecked usages — for each one, try to write a comment explaining what makes it safe. If you can’t, you’ve probably found a bug. And when you’re stuck on a type that can’t be Sendable, try @MainActor before anything else. For most view-related types, it’s the right call anyway.</p><p>One more thing: <a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0518-tilde-sendable.md">SE-0518</a>, accepted in March 2026 but hasn&#39;t shipped yet. When it does, it introduces. ~Sendable — a way to explicitly mark a type as non-Sendable even when the compiler might otherwise allow it to conform. It’s for types that should stay bound to a single concurrency domain and never leave. Still worth keeping an eye on when it lands.</p><p>The compiler isn’t protecting Swift from you. It’s protecting your future self from your present self — and honestly, that’s a trade I’m glad someone made.</p><p>If you’ve hit a Sendable gotcha that isn’t on this list, I’m genuinely curious — drop it in the comments.</p><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d682b0689db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Swift's Dictionary: Hash Tables, Collisions and Performance]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/inside-swifts-dictionary-hash-tables-collisions-and-performance-8eaecc75c367?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eaecc75c367</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 18:13:52 GMT</pubDate>
            <atom:updated>2025-08-30T18:15:47.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOmbP1oPHyV177FSU4n_sA.png" /></figure><p><em>Explore how Swift turns hashing into O(1) lookups — from collisions and probing to resizing and optimizations.</em></p><h3>Introduction</h3><p>When computer scientists talk about efficiency, few data structures are as iconic as the <strong>hash table</strong>. At its core, a hash table is a simple yet powerful idea: it stores values associated with unique keys and allows us to insert, look up, or remove those values in <em>constant time on average</em> — O(1).</p><p>The magic lies in the <strong>hash function</strong>. Instead of scanning through a list to find a key, the hash function transforms that key into an integer and uses it as an index into an underlying array. In the best case, this means that accessing an element takes no longer than a single array lookup.</p><p>Of course, reality is never perfect. Different keys can sometimes map to the same index — a situation known as a <strong>collision</strong>. Handling collisions efficiently is what makes hash tables both elegant and subtle. Techniques like <strong>open addressing</strong>, <strong>linear probing</strong>, or <strong>chaining</strong> exist to make sure that even when collisions occur, the performance of the structure remains close to O(1). Because of this balance between simplicity and speed, hash tables have become one of the fundamental building blocks of modern programming languages.</p><p>In Swift, you don’t need to reinvent the wheel. The standard library already gives you a battle-tested hash table implementation called <strong>Dictionary</strong>. On the surface, it behaves exactly as you would expect: a collection that maps keys to values, with average-case O(1) insertions, lookups, and removals. But behind this familiar API lies a carefully engineered data structure, optimized with techniques like open addressing, linear probing, and copy-on-write semantics — details that make Swift’s Dictionary both safe and extremely fast.</p><h3>The Basics: Keys and Hashable</h3><p>Every dictionary is built on the same principle: you provide a <strong>key</strong>, and it gives you back the <strong>value</strong>. But for the hash table under the hood to work, the key must conform to the <strong>Hashable</strong> protocol.</p><p>Conforming to Hashable means two things:</p><ol><li><strong>Stable equality</strong> — two keys that compare equal with == must always produce the same hash value during a single program run.</li><li><strong>Hashing support</strong> — each key must be able to feed itself into a Hasher, which produces an integer used to determine its bucket index.</li></ol><p>Here’s the important part:</p><p>⚠️ <strong>Hash values are not guaranteed to be equal across different program runs.</strong></p><p>This behavior is intentional. Since Swift 4.2, the standard library seeds the Hasher with a random value every time your program starts. This <strong>randomization defends against collision-based attacks</strong> that could otherwise degrade performance.</p><p>From Apple’s official documentation:</p><blockquote><em>“Hash values are not guaranteed to be equal across different executions of your program, and they are not guaranteed to be equal across different platforms. Do not save hash values to use during a future execution.”</em></blockquote><blockquote><a href="https://developer.apple.com/documentation/swift/hashable"><em>Swift Documentation — Hashable</em></a></blockquote><p>Because of this, you should <strong>never persist hash values</strong> (e.g., in a database or file) expecting them to be stable. Hashes are meant only for in-memory use during the lifetime of your process.\</p><p>To see this in practice, let’s try a quick experiment in Swift. If we create two strings with the same contents, their hashValue will be identical during a single run:</p><pre>let firstString = &quot;your_string&quot;<br>let secondString = &quot;your_string&quot;<br><br>print(firstString.hashValue)  //Output: 2475150862620269726<br>print(secondString.hashValue) //Output: 2475150862620269726</pre><p>This makes sense: two values that are equal with == must also produce the same hash value within the same execution.</p><p>But equal values don’t mean they share the same memory location. Each variable lives at a distinct address on the stack, which we can verify using withUnsafePointer:</p><pre>var firstString = &quot;your_string&quot;<br>var secondString = &quot;your_string&quot;<br><br>withUnsafePointer(to: &amp;firstString) { p in print(&quot;s1 address:&quot;, p) }<br>withUnsafePointer(to: &amp;secondString) { p in print(&quot;s2 address:&quot;, p) }<br><br>//Output: firstString address: 0x000000010310c1a0<br>//Output: secondString address: 0x000000010310c1b0</pre><p>The output will show two different addresses. Even though the contents are equal, they are separate variables with their own memory slots.</p><p>Finally, if you stop the program and run it again, you’ll notice that the hash values themselves are not stable and you get different values.</p><p>Before a key can be placed inside a dictionary, Swift first transforms it into a <strong>hash value</strong>. That hash value is then converted into a valid <strong>index</strong> pointing to a specific position in the underlying storage array. In other words, every key in a dictionary is reduced to an integer that determines where it should live internally.</p><p>By default, all of Swift’s basic types already conform to Hashable — integers, strings, booleans and more. That’s why you can freely use them as dictionary keys without writing any extra code.</p><p>But if you want to use your own custom type as a key, you need to explicitly conform to the Hashable protocol. The compiler will often synthesize this conformance for you if all stored properties are themselves Hashable.</p><pre>struct User: Hashable {<br>    let id: Int<br>    let name: String<br>}<br><br>// Works directly as a Dictionary key<br>var users: [User: Int] = [:]<br>users[User(id: 1, name: &quot;Ana&quot;)] = 100<br>users[User(id: 2, name: &quot;Bruno&quot;)] = 200</pre><p>If you need more control, you can implement == and hash(into:) manually. The hash(into:) method lets you combine the relevant properties into the Hasher.</p><pre>struct Point: Hashable {<br>    let x: Int<br>    let y: Int<br><br>    func hash(into hasher: inout Hasher) {<br>        hasher.combine(x)<br>        hasher.combine(y)<br>    }<br><br>    static func == (lhs: Point, rhs: Point) -&gt; Bool {<br>        lhs.x == rhs.x &amp;&amp; lhs.y == rhs.y<br>    }<br>}</pre><p>This way, Point instances can be used as dictionary keys while ensuring that equality and hashing remain consistent.</p><p>A good hash function matters. To make hash tables efficient, the function that turns keys into integers must meet three important criteria:</p><ul><li><strong>Fast</strong> — computing the hash should be quick, otherwise the constant-time promise of dictionary operations breaks down.</li><li><strong>Well-distributed</strong> — keys that are similar should not produce hash values that cluster together. The more uniform the distribution, the better.</li><li><strong>Collision-resistant</strong> — while collisions are inevitable, a good hash function minimizes their frequency, keeping lookup chains short and predictable.</li></ul><p>In Swift, the standard Hasher already provides these guarantees. Since Swift 4.2, it has been powered by a variant of <strong>SipHash</strong>, which is both fast and resistant to collision-based denial-of-service attacks.</p><p>In the next sections, we’ll explore how this transformation from hash value to index actually works, and what happens when two different keys end up pointing to the same slot.</p><h3>From Hash to Index</h3><p>Once a key has been converted into a hash value, the next step is to decide <strong>where</strong> in the dictionary that entry should live. The hash itself is just a large integer — often 64 bits on modern platforms. But we can’t simply use that raw number as an array index.</p><p>Imagine doing so: if a hash value is something like 15,837,291,112,904, we would need an array with more than fifteen trillion slots just to place it at that position. The result would be an array that is astronomically large, mostly empty, and completely impractical.</p><p>That’s why every hash table needs a <strong>conversion step</strong>: turn the big hash value into a valid index that falls within the current capacity of the dictionary. The goal is to do this conversion in a way that is <strong>simple, fast, and efficient</strong>.</p><p>There are two classic approaches to achieve this:</p><p><strong>Modulo operator</strong></p><p>The straightforward way is to take the hash and apply the modulo operator with the dictionary’s capacity:</p><pre>let moduleIndex  = hash % capacity</pre><p>This guarantees the result is always within the valid range. The downside? Modulo requires an integer division, which is relatively expensive for the CPU.</p><p><strong>Bitwise AND (Swift’s choice)</strong></p><p>Swift’s Dictionary takes a different route. By ensuring that the internal capacity is always a power of two (like 8, 16, 32…), it can replace the modulo with a simple bitmask:</p><pre>let bitwiseIndex = hash &amp; (capacity - 1)</pre><p>In practice, this just extracts the lower k bits of the hash, where capacity = 2^k. It’s mathematically equivalent to modulo, but dramatically faster because it avoids division.</p><p>This small design choice — powers of two combined with a bitmask — is one of the reasons why Swift dictionaries are so efficient.</p><pre><br>let yourStringKey = &quot;key_string_value&quot;<br>let hash: Int = yourStringKey.hashValue<br>let capacity = 8   // must be a power of two: 2, 4, 8, 16, ...<br>let bitwiseIndex = hash &amp; (capacity - 1)<br>let moduloIndex  = hash % capacity<br><br>print(&quot;hash: \(hash)&quot;)<br>print(&quot;capacity: \(capacity)&quot;)<br>print(&quot;bitwise index: \(bitwiseIndex)&quot;)<br>print(&quot;modulo index:  \(moduloIndex)&quot;)</pre><pre>hash: 9168509427520388836<br>capacity: 8<br>bitwise index: 4<br>modulo index:  4</pre><p>With this setup, we have a solid foundation: keys become hash values, and those hash values are turned into <strong>valid indices</strong> efficiently. Using a power-of-two capacity lets the runtime replace an expensive modulo with a cheap bitmask hash &amp; (capacity — 1), guaranteeing an index in 0..&lt;capacity even when the hash is negative. The result is a fast, predictable mapping from key → hash → index that keeps lookups, inserts, and removals on average at O(1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ktIjCNXsiHrzs0F48kS1g.png" /></figure><p>Next, we’ll see what happens when two different keys map to the <em>same</em> index — <strong>collisions</strong> — and how the dictionary resolves them.</p><h3>Collisions</h3><p>So far, we’ve seen how a hash table maps a key into a valid index. But what if two different keys happen to land on the same index? This is called a <strong>collision</strong>, and it’s an unavoidable fact of hashing. The question is not <em>if</em> collisions happen, but <em>how to deal with them efficiently</em>.</p><p>There are two classic strategies: <strong>separate chaining</strong> with linked lists and <strong>open addressing</strong> with probing.</p><h4>Linked Lists (Separate Chaining)</h4><p>One common way to handle collisions is called <strong>separate chaining</strong>. In this approach, each bucket in the table doesn’t just hold a single entry — it can hold a <strong>linked list</strong> of entries.</p><p>Imagine we insert two names: <em>John Smith and Sandra Dee</em>. By coincidence, they all hash to the same index, bucket [152]. With separate chaining, we don’t overwrite the existing entry. Instead, the bucket points to a linked list of all colliding keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*z-U_mVBQcx4oDkz4tQxfIA.webp" /></figure><p>All other buckets remain empty.</p><p>Looking up Sandra Dee works like this:</p><ol><li>Hash the key “Sandra Dee” → bucket [152].</li><li>Traverse the linked list: check John Smith, then Sandra Dee.</li><li>Once found, return the associated value.</li></ol><p>This method has a few nice properties:</p><ul><li>Insertions are straightforward: new items are just appended to the list.</li><li>The hash table can grow in capacity without moving existing elements around.</li></ul><p>But there are trade-offs too:</p><ul><li>Every collision adds a new node with extra pointers, which increases <strong>memory overhead</strong>.</li><li>Following linked nodes scattered across memory reduces <strong>cache efficiency</strong>, making lookups slower than with a flat array.</li></ul><p>Because of these trade-offs, Swift’s Dictionary does <strong>not</strong> use linked lists for collision handling. Instead, it relies on a different strategy — <strong>linear probing</strong> — which we’ll explore next.</p><h4>Linear Probing (Open Addressing)</h4><p>Swift’s Dictionary doesn’t use linked lists to resolve collisions. Instead, it relies on <strong>open addressing with linear probing</strong>, where each bucket can store only one entry. When two keys land on the same index, the dictionary searches for the next free slot in the array.</p><p>Let’s take the example in the diagram, with <em>John Smith</em> and <em>Sandra Dee</em>.</p><ol><li>The key <strong>“John Smith”</strong> is hashed, and the hash maps to <strong>bucket [873]</strong>. Since that bucket is empty, John Smith is stored directly there</li><li>Later, the key <strong>“Sandra Dee”</strong> is also hashed, and by coincidence it maps to the <strong>same index [873]</strong>. But bucket [<strong>873</strong>] is already taken by John Smith.</li><li>Instead of chaining them together, the dictionary probes forward in the array</li><li>Bucket [<strong>874</strong>]: free → Sandra Dee is placed there.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMHH_4DcwUcUijBIaW_3_g.png" /></figure><p>Now, searching for <strong>Sandra Dee</strong> works like this:</p><ul><li>Start at her original hash index, [873].</li><li>Compare the stored key (<em>John Smith</em>) → not a match.</li><li>Move to the next bucket, [874].</li><li>Compare again → match found (<em>Sandra Dee</em>).</li></ul><p>This illustrates the essence of linear probing: when a collision occurs, keep moving forward until an open slot (or the desired key) is found.</p><p>The benefit of this approach is that all keys and values remain inside a <strong>contiguous array</strong>, which is extremely efficient for CPU caching and iteration. But it also means that when the table gets crowded, probing chains can get longer — making resizing and load factor management critical.</p><p>Swift optimizes further by using <strong>backward shift deletion</strong> when removing entries: instead of leaving empty “tombstones,” it shifts subsequent elements backward to maintain a valid probing sequence.</p><blockquote><em>⚠️ </em><strong><em>Note</em></strong></blockquote><blockquote><em>Everything we’ve discussed about how Swift’s Dictionary resolves collisions — hashing with bitwise operation, indexing, linear probing, or backward shift deletion — comes from examining the </em><a href="https://github.com/swiftlang/swift/blob/fcc1d00a05b1db4dae8b094f4e82c7f4e9522831/stdlib/public/core/Dictionary.swift#L18"><em>Swift Standard Library source code</em></a><em>.</em></blockquote><blockquote><em>These are </em><strong><em>implementation details</em></strong><em>, not part of the official API contract. Apple may change them at any time to improve performance or memory efficiency.</em></blockquote><blockquote><em>As a developer, what you should rely on is only what’s documented in the </em><a href="https://developer.apple.com/documentation/swift/dictionary"><em>official Swift documentation</em></a><em>:</em></blockquote><blockquote>- Dictionary maps unique keys to values</blockquote><blockquote>- Keys must conform to Hashable.</blockquote><blockquote>- Insertions, lookups, and deletions are O(1) on average.</blockquote><blockquote><em>Everything else is fascinating to study, but not guaranteed to remain the same across Swift versions.</em></blockquote><p>So which strategy is better? The truth is that both have strengths and weaknesses. <strong>Separate chaining</strong> shines in theory: insertions are simple, deletions are straightforward, and performance degrades more gracefully as the table fills. The downside is memory overhead (extra pointers, heap allocations) and poor cache locality. <strong>Linear probing</strong>, on the other hand, looks worse on paper — the average probe length grows quickly as the load factor increases — but in practice it often wins, because all data lives in a contiguous array. Modern CPUs are extremely good at scanning memory sequentially, and this cache-friendliness more than offsets the extra probes at realistic load factors.</p><p>This is why Swift’s standard library team chose <strong>open addressing with linear probing</strong> for Dictionary. Collisions still happen, but the combination of a high-quality hash function, randomized seeding, and automatic resizing keeps the load factor low enough that probing chains remain short. In real programs, that means most lookups require only one or two probes — while still benefiting from the speed of scanning flat memory rather than chasing pointers in linked lists.</p><h4>How Likely Are Collisions, Really?</h4><p>At this point you might be wondering: if hash tables are supposed to give constant-time lookups, how often do collisions actually happen? The short answer is: <strong>they are inevitable, but surprisingly rare in practice.</strong></p><p>A hash function maps an infinite space of possible keys into a fixed range of integers. That means, by definition, different keys will sometimes map to the same bucket. The frequency of collisions depends on three factors:</p><ol><li><strong>The hash function itself</strong> — A good function spreads keys uniformly, making collisions less frequent. Swift’s Hasher (based on SipHash) was designed to provide strong distribution.</li><li><strong>The load factor (n ÷ m).</strong> This is the ratio between the number of stored elements (<em>n</em>) and the total number of buckets (<em>m</em>). For example, if a dictionary is half full (n ÷ m = 0.5), collisions are less common. If it’s 90% full (n ÷ m = 0.9), collisions are much more likely. That’s why Swift dictionaries automatically resize before they become too crowded.</li><li><strong>The number of keys relative to the bucket space</strong> — This is the classic <em>birthday paradox</em>. Even with a large space of possible hashes, once you insert enough keys, the probability of at least one collision rises quickly.</li></ol><p>For example, if a dictionary has 1,000 buckets and you insert about 40 keys, the probability of a collision is already close to 50%. By the time you insert 100 keys, a collision is almost certain.</p><p>That sounds scary, but here’s the good news:</p><ul><li>In practice, <strong>collisions don’t ruin performance</strong>. The probing strategy resolves them efficiently, and average lookup times stay close to O(1).</li><li>Swift’s Dictionary is engineered to keep chains short by resizing early and using a secure, well-distributed hash function.</li></ul><p>So while collisions are guaranteed to exist, they are <strong>rare enough and cheap enough to handle</strong> that you don’t need to worry about them as an app developer.</p><h3>Building a Tiny Hash Table (Chaining + Modulo)</h3><p>We’ll implement a minimal hash table that:</p><ul><li>Uses <strong>linked lists</strong> to handle collisions (separate chaining), and</li><li>Maps a hash value to a <strong>valid index</strong> with the <strong>modulo operator</strong>.</li></ul><h4>Step 1 — A node for our chain</h4><p>Each bucket will hold the <strong>head</strong> of a singly linked list. Every node stores a key, a value, and a pointer to the next node.</p><pre>final class Node&lt;Key: Hashable, Value&gt; {<br>    var key: Key<br>    var value: Value<br>    var nextNode: ListNode?<br><br>    init(key: Key, value: Value, nextNode: ListNode? = nil) {<br>        self.key = key<br>        self.value = value<br>        self.nextNode = nextNode<br>    }<br>}</pre><h4>Step 2 — Buckets and basic storage</h4><p>Our table is an array of optional Node heads. We’ll start small and grow later.</p><pre>final class HashTable&lt;Key: Hashable, Value&gt; {<br>    private var buckets: [Node&lt;Key, Value&gt;?]<br>    private(set) var count = 0<br><br>    init(minimumCapacity: Int = 8) {<br>        let capacity = max(1, minimumCapacity)<br>        self.buckets = Array(repeating: nil, count: capacity)<br>    }<br>}</pre><h4>Step 3 — From hash to index (with %)</h4><p>We turn a key into an integer hash, then into a <strong>valid</strong> index 0..&lt;buckets.count. To avoid negative results from %, we cast the hash to UInt first.</p><pre>extension HashTable {<br><br>    private func bucketIndex(for key: Key) -&gt; Int {<br>        let normalizedHash = UInt(bitPattern: key.hashValue)<br>        return Int(normalizedHash % UInt(buckets.count))<br>    }<br>}</pre><h4>Step 4 — Inserting (or updating) a key</h4><p>To set a value:</p><ol><li>compute the bucket index,</li><li>walk the list: if the key exists, <strong>update</strong>; otherwise, <strong>prepend</strong> a new node.</li></ol><pre>extension HashTable {<br><br>    @discardableResult<br>    func set(_ key: Key, to value: Value) -&gt; Value? {<br>        let index = bucketIndex(for: key)<br>        var currentNode = buckets[index]<br>        var previousNode: Node&lt;Key, Value&gt;? = nil<br><br>        while let node = currentNode {<br>            if node.key == key {<br>                let oldValue = node.value<br>                node.value = value<br>                return oldValue<br>            }<br>            previousNode = node<br>            currentNode = node.nextNode<br>        }<br><br>        // Not found: insert at head (O(1))<br>        let newHead = Node&lt;Key, Value&gt;(key: key, value: value, nextNode: buckets[index])<br>        buckets[index] = newHead<br>        count += 1<br>        return nil<br>    }<br>}</pre><p><strong>Why prepend?</strong> It’s O(1) and keeps the code simple. (Hash tables don’t promise insertion order.)</p><h4>Step 5 — Looking up a key</h4><p>Hash → index → traverse until we <strong>find</strong> the key or <strong>hit nil</strong>.</p><pre>extension HashTable {<br>    <br>func get(_ key: Key) -&gt; Value? {<br>        let index = bucketIndex(for: key)<br>        var currentNode = buckets[index]<br><br>        while let node = currentNode {<br>            if node.key == key { return node.value }<br>            currentNode = node.nextNode<br>        }<br>        return nil<br>    }<br>}</pre><h4>Step 6 — Removing a key</h4><p>Unlink the matching node from the chain (standard singly linked list delete).</p><pre>extension HashTable {<br>   <br> @discardableResult<br>    func remove(_ key: Key) -&gt; Value? {<br>        let index = bucketIndex(for: key)<br>        var currentNode = buckets[index]<br>        var previousNode: ListNode&lt;Key, Value&gt;? = nil<br><br>        while let node = currentNode {<br>            if node.key == key {<br>                // unlink<br>                if let prev = previousNode {<br>                    prev.nextNode = node.nextNode<br>                } else {<br>                    buckets[index] = node.nextNode<br>                }<br>                count -= 1<br>                return node.value<br>            }<br>            previousNode = node<br>            currentNode = node.nextNode<br>        }<br>        return nil<br>    }<br>}</pre><p>With the completed structure, we can now use it as you would use a regular dictionary, but without the subscription part:</p><pre>let table = HashTable&lt;String, Int&gt;(minimumCapacity: 8)<br>table.set(&quot;Ana&quot;, to: 25)<br>table.set(&quot;Bruno&quot;, to: 30)<br>table.set(&quot;Bia&quot;, to: 28)<br><br>print(table.get(&quot;Bia&quot;) ?? -1)   // 28<br>table.set(&quot;Ana&quot;, to: 26)         // update<br>print(table.get(&quot;Ana&quot;) ?? -1)    // 26<br><br>table.remove(&quot;Bruno&quot;)<br>print(table.get(&quot;Bruno&quot;) as Any) // nil</pre><p>The beauty of rolling out our own hash table is that <strong>we control every detail</strong>. Unlike Swift’s built-in Dictionary, which hides its internals for good reason, our custom structure is fully transparent — and therefore open to customization. We could experiment with <strong>different collision strategies</strong> (switching from chaining to open addressing), add <strong>custom resizing policies</strong> (shrink the table when it’s too empty, not only grow it), or even track <strong>statistics</strong> such as average chain length to measure performance. For educational purposes, we might also expose debug views to print the contents of each bucket, making collisions visible in real time.</p><p>In short, this version is not meant to outperform Dictionary, but to give us the freedom to tweak, extend, and play with the internals of a hash table in ways that the standard library doesn’t allow.</p><h3>Resizing and Load Factor</h3><p>A hash table can’t grow indefinitely inside a fixed array. At some point, too many elements will pile up and collisions would become unmanageable. To prevent this, dictionaries keep track of their <strong>load factor</strong> — the ratio between the number of stored entries and the total number of buckets.</p><p>When the load factor approaches a threshold (around <strong>0.75</strong> in Swift), the dictionary automatically <strong>resizes</strong>:</p><ol><li>Allocate a new, larger array (usually doubling capacity).</li><li><strong>Rehash</strong> every key to its new position in the bigger array.</li></ol><p>Resizing sounds expensive — it costs <strong>O(n)</strong> because every element must be moved. But here’s the trick: resizing doesn’t happen often. Because capacity grows geometrically, each element is rehashed only a handful of times across the entire lifetime of the table. That’s why the <strong>amortized cost</strong> of insertions, deletions, and lookups remains <strong>O(1)</strong> on average.</p><h4>Seeing it in action</h4><p>Swift doesn’t expose load factor directly, but we can peek into the <strong>capacity</strong> of a dictionary as we insert elements:</p><pre>var numbers: [Int: Int] = [:]<br><br>for i in 0..&lt;50 {<br>    numbers[i] = i<br>    if i % 10 == 0 {   // print capacity every 10 inserts<br>        print(&quot;Count:&quot;, numbers.count, &quot;Capacity:&quot;, numbers.capacity)<br>    }<br>}</pre><p>Sample output (values may vary by Swift version):</p><pre>Count: 1 Capacity: 1<br>Count: 11 Capacity: 12<br>Count: 21 Capacity: 24<br>Count: 31 Capacity: 48<br>Count: 41 Capacity: 48</pre><p>Notice how the <strong>count</strong> grows linearly, but the <strong>capacity</strong> jumps at specific moments, usually doubling in size. This is exactly when the dictionary decides it’s time to resize and rehash.</p><h3>Key Optimizations in Swift’s Dictionary</h3><p>Swift’s Dictionary isn’t just a textbook hash table — it comes with several optimizations that make it competitive in real-world apps:</p><ul><li><strong>Cache locality.</strong> Because it uses an internal array rather than linked nodes, Swift benefits from contiguous memory. Modern CPUs are extremely good at scanning arrays, which makes linear probing faster in practice than it looks on paper.</li><li><strong>Copy-on-Write (COW).</strong> Dictionary is a <em>value type</em>, which means copying it should, in theory, duplicate the entire storage. In practice, Swift delays copying until one of the copies is modified. This <strong>copy-on-write</strong> strategy combines value semantics (safe, predictable) with reference-like performance.</li><li><strong>Native vs. bridged storage.</strong> Swift dictionaries integrate seamlessly with Objective-C’s NSDictionary. Under the hood, Swift can store entries in a native format for maximum performance, or bridge to NSDictionary when interacting with Cocoa APIs. This bridging is invisible to you, but it ensures interoperability without sacrificing speed.</li></ul><h3>What You Need to Know for the Interview!</h3><p>If you’re preparing for a coding interview, the goal is not to memorize Swift’s internal implementation details. Instead, focus on the <strong>concepts</strong> and how to explain them clearly. Here’s what really matters:</p><ul><li><strong>Definition.</strong> A hash table is a data structure that maps keys to values in average O(1) time using a hash function.</li><li><strong>Hashable requirement.</strong> In Swift, dictionary keys must conform to Hashable. That means they can generate a stable hash during a program run and be compared with ==.</li><li><strong>Hash → index mapping.</strong> Explain why we can’t just use the raw hash as an array index. Mention modulo (%) and bitmask (&amp; (capacity — 1)) as common strategies.</li><li><strong>Collisions.</strong> Collisions are inevitable. Be ready to describe at least two strategies: <strong>Separate chaining</strong> (linked lists) and <strong>Open addressing</strong> (linear probing, which Swift uses).</li><li><strong>Load factor and resizing.</strong> Why dictionaries grow as they fill up (rehash, amortized O(1)).</li><li><strong>Complexity.</strong> Average O(1) for lookup, insert, delete. Worst case O(n) if everything collides.</li><li><strong>Practical optimizations.</strong> Swift dictionaries are cache-friendly, use copy-on-write for efficiency, and integrate with NSDictionary.</li></ul><blockquote><em>💡 </em><strong><em>Pro tip:</em></strong><em> In interviews, it’s less about knowing Swift’s internals and more about showing that you understand </em>why<em> hash tables are efficient, what can go wrong (collisions, poor hash functions), and how they’re typically handled.</em></blockquote><h3>Conclusion</h3><p>At first glance, a dictionary may look like “just a map” from keys to values. But as we’ve seen, it’s actually a highly optimized data structure built on top of hashing, probing, load factors, and clever memory tricks. Behind the simple syntax lies decades of computer science and engineering decisions.</p><p>If you want to deepen your understanding, try running small experiments in a Swift Playground:</p><ul><li>Print out bucket indices using % and &amp; masks.</li><li>Force collisions to see how probing sequences work.</li><li>Inspect capacity as you insert elements to watch resizing in action.</li></ul><p>These hands-on tests make the abstract ideas tangible.</p><p>And this is only the beginning. Swift’s Set is built on the exact same foundation as Dictionary, just storing keys without values. In future articles, we can explore how sets compare to dictionaries, or even dive into performance tuning — measuring how different load factors and access patterns impact real-world speed.</p><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eaecc75c367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Queues in Swift: Data Structures Every iOS Developer Must Know for Interviews]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/mastering-queues-in-swift-data-structures-every-ios-developer-must-know-for-interviews-4d93d5fa1b38?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d93d5fa1b38</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 03:02:44 GMT</pubDate>
            <atom:updated>2025-08-22T03:02:44.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDXhZTRR--zCe9xgW2dgFA.png" /></figure><p>Discover how the Queue data structure works, implement it in Swift, and see where it appears in iOS. Everything explained simply and straight to the point for your interviews.</p><h3>Introduction</h3><p>When it comes to <strong>technical interviews</strong> for software engineering roles, one topic almost always shows up: <strong>data structures</strong>.</p><p>They are the foundation of how information is organized, accessed, and manipulated in a program. Demonstrating that you can explain — and implement — these structures proves not only theoretical knowledge, but also the ability to apply it in real-world scenarios.</p><p>Among all data structures, one of the most frequently asked about is the <strong>Queue</strong>.</p><p>It’s conceptually simple yet extremely present in real systems: from scheduling processes in operating systems to managing tasks in iOS apps with DispatchQueue.</p><p>Because of this mix of <strong>simplicity</strong> and <strong>practical relevance</strong>, queues often appear in interviews — sometimes in conceptual questions (“What’s the difference between a Queue and a Stack?”), and sometimes in coding challenges.</p><p>In this article, we’ll explore:</p><ul><li>What a Queue is in theory.</li><li>How to implement one in Swift and what decisions we have to make.</li><li>The basic operations and their time/space complexities.</li><li>And finally, how this concept shows up in everyday iOS development.</li></ul><h3>What is a Queue?</h3><p>A <strong>Queue</strong> is a <strong>linear data structure</strong> that follows the principle of <strong>FIFO — First In, First Out</strong>.</p><p>In other words, the <strong>first element added</strong> is always the <strong>first one to be removed</strong>.</p><h4>Real-life Analogy</h4><p>Think about standing in line at the supermarket checkout.</p><ul><li>The first person to arrive will be the first one to be served.</li><li>New people join the line at the back.</li><li>No one can “jump” directly to the front (unless you want angry stares!).</li></ul><p>This is exactly how a Queue works in computer science.</p><h4>Core Operations</h4><ul><li><strong>enqueue(element)</strong> → inserts an element at the <em>end</em> of the Queue.</li><li><strong>dequeue()</strong> → removes and returns the element at the <em>front</em> of the Queue.</li><li><strong>peek/front()</strong> → returns the element at the <em>front</em> without removing it.</li><li><strong>isEmpty()</strong> → checks if the Queue has no elements.</li></ul><p>Queues may look simple, but their predictable behavior makes them one of the most useful and fundamental data structures in computer science and software engineering.</p><h3>Implementing a Queue in Swift</h3><p>There are two common ways to implement a Queue in Swift: one using an <strong>array</strong> as the underlying storage, and another using a <strong>linked list</strong>. Both follow the same <strong>FIFO</strong> principle, but the performance of their core operations differs.</p><h4>Queue with Array</h4><p>The most straightforward approach is to back the Queue with a Swift array. Adding elements to the end is trivial — Swift’s append is an <strong>amortized O(1)</strong> operation. The catch comes when removing elements from the front. If you call removeFirst(), Swift has to shift all the remaining items one position to the left, which makes it an <strong>O(n)</strong> operation.</p><p>Here’s a simple implementation:</p><pre>struct ArrayQueue&lt;T&gt; {<br>    private var storage: [T] = []<br><br>    var isEmpty: Bool { storage.isEmpty }<br><br>    var peek: T? { storage.first }<br><br>    mutating func enqueue(_ value: T) {<br>        storage.append(value)<br>    }<br><br>    mutating func dequeue() -&gt; T? {<br>        isEmpty ? nil : storage.removeFirst()<br>    }<br>}</pre><p>This version works well for small queues, but performance degrades if you do lots of dequeues in large collections.</p><h4>Queue with Linked List</h4><p>To avoid the cost of shifting elements, we can use a <strong>linked list</strong>. With a pointer to both the head and tail, inserting at the end and removing from the front are both <strong>O(1)</strong> operations.</p><pre>final class ListNode&lt;T&gt; {<br>    var value: T<br>    var next: ListNode&lt;T&gt;?<br>    init(_ value: T) { self.value = value }<br>}<br><br>struct LinkedListQueue&lt;T&gt; {<br>    private var head: ListNode&lt;T&gt;? = nil<br>    private var tail: ListNode&lt;T&gt;? = nil<br><br>    var isEmpty: Bool { head == nil }<br>    var peek: T? { head?.value }<br><br>    mutating func enqueue(_ value: T) {<br>        let node = ListNode(value)<br>        if let t = tail {<br>            t.next = node<br>        } else {<br>            head = node<br>        }<br>        tail = node<br>    }<br><br>    mutating func dequeue() -&gt; T? {<br>        guard let h = head else { return nil }<br>        head = h.next<br>        if head == nil { tail = nil }<br>        return h.value<br>    }<br>}</pre><p>Here, both enqueue and dequeue complete in constant time, regardless of the queue size. The trade-off is slightly more complex code and a bit of memory overhead for the linked list nodes.</p><h4>Complexity Comparison</h4><ul><li>With <strong>arrays</strong>, enqueue is <strong>O(1) (amortized)</strong>, but dequeue is <strong>O(n)</strong>.</li><li>With <strong>linked lists</strong>, both enqueue and dequeue are<strong> O(1)</strong>.</li><li>In both cases, peek and isEmpty are constant time.</li><li>Space complexity is <strong>O(n</strong>) in both, though the linked list carries a per-node pointer overhead.</li></ul><p><strong>In practice:</strong> if your queues are small or mostly append-only, the array implementation is simple and fine. But if you expect heavy use of dequeues at scale, the linked list version guarantees consistent performance.</p><p>Now that we’ve seen the basic implementations, let’s look at some common variations you might encounter in interviews:</p><h3>Variations of Queues</h3><p>While the standard queue follows the strict <strong>FIFO</strong> rule, there are several variations that extend its behavior. Two of the most common — and the ones you’re most likely to encounter in interviews — are the <strong>Deque</strong> and the <strong>Priority Queue</strong>.</p><h4>Deque (Double-Ended Queue)</h4><p>A <strong>Deque</strong> (pronounced <em>deck</em>) is a queue that allows insertion and removal at <strong>both ends</strong>.</p><ul><li>You can add or remove elements from the front <em>and</em> the back.</li><li>This makes it more flexible than a normal queue, since it can behave like both a queue <strong>and</strong> a stack.</li></ul><p>In Swift, you might simulate a deque with an Array by using both append() and removeLast() for the back and insert(_:at:) and removeFirst() for the front. However, the standard library doesn’t yet provide a dedicated Deque type, so efficient implementations often rely on ring buffers.</p><p><strong>In interviews:</strong> A common question is: <em>“How would you implement a deque so that both front and back operations are O(1)?”</em> The expected answer usually involves a circular buffer or a doubly linked list.</p><h4>Priority Queue</h4><p>A <strong>Priority Queue</strong> changes the removal rule: instead of simply removing the element that arrived first, it removes the element with the <strong>highest priority</strong>.</p><ul><li>Think of a hospital emergency room: the patient in most critical condition is treated before someone with a mild fever, even if they arrived later.</li><li>Under the hood, priority queues are often implemented using a <strong>heap</strong>, which makes both insertion and removal of the “highest priority” element efficient at <strong>O(log n)</strong>.</li></ul><p><strong>In interviews:</strong> Priority queues are frequently tested in the form of:</p><ul><li><em>“Implement a priority queue in Swift.”</em></li><li><em>“What data structure would you use to always access the minimum or maximum element quickly?”</em> (answer: a heap, which backs the priority queue).</li><li>You might also see them in algorithm challenges like <strong>Dijkstra’s shortest path</strong> or <strong>task schedulers</strong>.</li></ul><h4>Why They Matter in Interviews</h4><p>These variations show up because they test whether you understand the <strong>limitations of the basic queue</strong> and how to extend it to solve more complex real-world problems. Even if you never implement a deque or priority queue from scratch in production Swift code, being comfortable explaining them shows strong fundamentals.</p><h3>Typical Interview Questions on Queues</h3><p>Because queues are simple but versatile, they’re a favorite topic in technical interviews. The goal isn’t only to check if you can memorize the operations, but whether you understand the <strong>trade-offs, complexities, and real-world applications</strong>.</p><p>Here are some of the most common types of questions you might face:</p><h4>1. Implement a Queue from Scratch</h4><p>This is a classic. The interviewer might say:</p><blockquote>“Implement a queue in Swift with enqueue, dequeue, and peek operations.”</blockquote><p>Sometimes they’ll push further:</p><ul><li><em>“What’s the complexity of each operation in your implementation?”</em></li><li><em>“Can you make dequeue run in O(1) time?”</em></li></ul><p>This usually opens the door for you to compare <strong>array vs linked list</strong> implementations, or even show how to optimize an array-backed queue with a ring buffer.</p><h4>2. Compare Queues and Stacks</h4><p>Another frequent conceptual question:</p><blockquote>“What’s the difference between a stack and a queue?”</blockquote><p>A good answer highlights:</p><ul><li><strong>Queue:</strong> FIFO (first in, first out).</li><li><strong>Stack:</strong> LIFO (last in, first out).</li></ul><p>Some interviewers will then ask you to describe <strong>when to use each</strong> in real-world scenarios.</p><h4>3. Advanced Variations</h4><p>You might be asked about queue extensions:</p><ul><li><em>“How would you implement a deque with O(1) operations at both ends?”</em></li><li><em>“What’s a priority queue, and how would you implement one in Swift?”</em></li></ul><p>Even if you don’t code the full solution, being able to explain <strong>why a heap is a good fit</strong> for a priority queue usually earns points.</p><h4>4. Algorithmic Challenges Using Queues</h4><p>Finally, queues often appear as part of larger problems. For example:</p><ul><li><strong>Breadth-First Search (BFS):</strong> a queue is used to explore nodes level by level.</li><li><strong>Task scheduling:</strong> jobs are queued and executed in order.</li><li><strong>Producer-consumer problems:</strong> where multiple producers add to a queue and consumers remove from it.</li></ul><p>In these scenarios, the interviewer is checking whether you know <strong>which data structure to reach for</strong> when solving the problem.</p><h3>Queues in iOS</h3><p>So far, we’ve looked at queues as a data structure. But if you’ve ever built an iOS app, you’ve already used them — just in a different form.</p><p>In iOS, the most common appearance of queues is through <strong>Grand Central Dispatch (GCD)</strong> and the DispatchQueue API. Here, a queue isn’t about storing numbers or strings, but about <strong>scheduling blocks of code</strong> to run in a predictable order.</p><h4>DispatchQueue</h4><p>A DispatchQueue is literally a FIFO queue of tasks. When you call async or sync, your block is enqueued, and the system decides when to execute it.</p><pre>let queue = DispatchQueue(label: &quot;com.example.myqueue&quot;)<br><br>queue.async {<br>    print(&quot;Task 1&quot;)<br>}<br><br>queue.async {<br>    print(&quot;Task 2&quot;)<br>}</pre><p>Even though tasks may execute on different threads, each queue still respects the <strong>FIFO order</strong> — Task 1 will start before Task 2 in the serial queue above.</p><h4>Main Queue vs Background Queues</h4><ul><li><strong>Main queue</strong> → a serial queue tied to the main thread, responsible for updating the UI.</li><li><strong>Global queues</strong> → concurrent queues provided by the system for background work.</li></ul><p>Example: fetching data in the background and updating the UI on the main queue:</p><pre>DispatchQueue.global().async {<br>    let data = fetchData()<br>    DispatchQueue.main.async {<br>        self.label.text = data.title<br>    }<br>}</pre><p>This pattern is so common that almost every iOS developer uses it daily — without always realizing they’re working with queues in the data-structure sense.</p><h4>Why This Matters</h4><p>Understanding queues in iOS is valuable for two reasons:</p><ol><li>It connects the <strong>theory</strong> (FIFO, enqueue, dequeue) with your <strong>day-to-day Swift code</strong>.</li><li>It gives you a stronger story to tell in interviews: not only can you implement a queue from scratch, but you can also explain how Apple uses the same concept to manage concurrency in apps.</li></ol><h3>Conclusion</h3><p>The <strong>Queue</strong> is one of the simplest data structures you’ll encounter, but also one of the most fundamental. Its FIFO nature makes it easy to grasp, yet powerful enough to appear in countless algorithms and real-world systems.</p><p>That’s why it’s such a common topic in interviews: it tests your ability to reason about <strong>ordering, efficiency, and concurrency</strong> all at once.</p><p>And as we’ve seen, queues aren’t just theory. In iOS development, they show up every day in DispatchQueue and OperationQueue, powering concurrency and keeping our apps responsive.</p><p>If you want to solidify what you’ve learned, the best next step is hands-on practice. Try implementing your own queue in Swift, experiment with both arrays and linked lists, and then challenge yourself with some <a href="https://leetcode.com/problem-list/queue/">queue-related <strong>LeetCode</strong> problems</a>.<strong> </strong>You’ll not only be ready for interview questions, but you’ll also gain a deeper appreciation for how this simple structure underpins so much of modern software.</p><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d93d5fa1b38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Stacks in iOS: What You Need to Know for Your Interview]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/mastering-stacks-in-ios-what-you-need-to-know-for-your-interview-60a4c2d02d1e?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a4c2d02d1e</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 03:08:14 GMT</pubDate>
            <atom:updated>2025-08-18T03:08:14.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7MvyVLh0uEqNT9lf8fcUg.png" /></figure><p>A Complete Guide to understanding stacks, real-world iOS use cases, and how to implement your own in Swift.</p><h3>Introduction</h3><p>In computer science, a <strong>stack</strong> is one of the most fundamental data structures. It represents a collection of elements with two primary operations: adding an element (<strong>push</strong>) and removing the most recently added element (<strong>pop</strong>). Unlike arrays where you can access any element directly, stacks enforce a strict access policy.</p><p>This access model is governed by the <strong>LIFO principle — Last In, First Out</strong>. The last item you push onto the stack is always the first one to come out. Think of a stack of plates in a cafeteria: you always add a new plate on top, and when you need one, you take from the top.</p><p>Stacks matter in everyday programming because they appear everywhere — from <strong>low-level execution</strong> (the call stack that powers function calls) to <strong>high-level features</strong> you use in iOS development, such as navigation flows or undo/redo functionality. Understanding stacks gives you the foundation to reason about both how the system works under the hood and how to build features in your own apps.</p><h3>Stacks Behind the Scenes in iOS</h3><p>Stacks are not just an abstract data structure you learn in theory — they are deeply embedded in the way iOS (and most operating systems) function at runtime. Here are a few critical places where stacks come into play:</p><h4>The Call Stack</h4><p>Every time you call a function in Swift, iOS pushes a new <strong>stack frame</strong> onto the call stack. This frame contains information such as:</p><ul><li>The function’s local variables.</li><li>The parameters passed into the function.</li><li>The return address (so the system knows where to continue execution once the function finishes).</li></ul><p>When the function completes, the frame is popped from the stack, and execution resumes at the correct point. This is why recursive functions, for example, can lead to a <strong>stack overflow</strong> if the call stack grows too deep.</p><h4>Thread Stacks</h4><p>Each thread created in iOS has its own dedicated stack memory. This stack is used to store local variables, manage execution state, and keep function call frames separate from other threads. If you’ve ever worked with <strong>Grand Central Dispatch (GCD)</strong> or <strong>async/await</strong> in Swift, behind the scenes each thread is managing its own stack.</p><h4>Exception Handling and Stack Unwinding</h4><p>When an error or exception occurs, iOS performs <strong>stack unwinding</strong>, which means it pops frames from the call stack until it finds a suitable error handler. This mechanism ensures that resources are cleaned up properly while maintaining program stability.</p><p>Understanding these low-level uses of stacks helps explain why concepts like <strong>recursion depth</strong>, <strong>multithreading</strong>, and <strong>error handling</strong> behave the way they do in Swift. In the next section, we’ll look at how stacks are surfaced in <strong>iOS APIs </strong>you use daily, such as navigation and undo operations.</p><h3>Stacks in iOS APIs</h3><p>Beyond the system internals, Apple’s frameworks expose the idea of stacks in ways that are directly useful for app developers. You may not always think of them as stacks, but the principle of <strong>Last In, First Out</strong> underlies many iOS APIs you already use.</p><h4>UINavigationController</h4><p>The most obvious example is <strong>UINavigationController</strong>.</p><ul><li>When you call pushViewController(_:animated:), the new screen is added on top of the navigation stack.</li><li>When you call popViewController(animated:), the top-most screen is removed, revealing the one beneath it.</li></ul><p>This makes navigation in UIKit a textbook implementation of a stack: screens are stacked as the user drills down into content and popped when going back.</p><h4>SwiftUI’s NavigationStack</h4><p>Introduced in iOS 16, NavigationStack brings a declarative way of managing navigation with a stack-like structure. Instead of imperatively pushing and popping, you work with a data-driven model that represents the stack of destinations. The principle is the same: the most recent view is on top, and removing it takes you back.</p><h4>UndoManager</h4><p>Another example is UndoManager, which powers undo/redo functionality in apps.</p><ul><li>Every action you register with the undo manager is pushed onto a stack.</li><li>When the user requests an undo, the manager pops the most recent action and executes it in reverse.</li><li>Redo works with a secondary stack, replaying actions that were undone.</li></ul><p>These APIs demonstrate that stacks are not just theoretical — they are part of the tools Apple gives you to structure user flows, manage state, and coordinate UI changes.</p><h3>Real-World Analogies</h3><p>Sometimes the best way to understand a data structure is to connect it with something we already know. Stacks appear in many everyday situations, and these analogies make the <strong>Last In, First Out (LIFO)</strong> principle intuitive:</p><h4>Stack of Plates in a Cafeteria</h4><p>Imagine a cafeteria where clean plates are stacked one on top of another. When a new plate is washed, it’s added to the <strong>top</strong> of the stack. When someone needs a plate, they also take it from the <strong>top</strong>. You never pull a plate from the bottom — that’s exactly how push and pop work in a stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*QWacz_NemdK5r2BOQlmG2Q.png" /></figure><h4>Browser History Navigation</h4><p>When you navigate through web pages, each new page is pushed onto a stack. Hitting the back button pops the last page you visited, revealing the previous one. Going forward works like pushing those pages back onto the stack again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*biPJ-wgnkiXfSnmOQaPbqg.png" /></figure><h4>Undo/Redo in Text Editors</h4><p>Every time you type or delete text, that action is stored on an undo stack. Pressing <strong>Undo</strong> pops the last action, restoring the previous state. Redo uses another stack to reapply the undone changes. This is a perfect example of two stacks working together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*LPhFm-1_roBnDp52O3AE3g.png" /></figure><h3>Choosing the Backing Structure: Array vs. Linked List</h3><p>When implementing a stack in Swift, two natural choices are a <strong>contiguous array </strong>and a <strong>singly linked list</strong>. Both can support push/pop at the top in constant time under the right conditions — but their <em>real-world</em> performance characteristics differ a lot on iOS.</p><h3>Arrays (Array&lt;T&gt;)</h3><ul><li><strong>Amortized O(1) push/pop at the end: </strong>Appending to Array is amortized O(1) because Swift grows capacity geometrically (reallocations happen occasionally). Removing with removeLast() is O(1).</li><li><strong>Excellent cache locality: </strong>Elements live contiguously in memory, which is CPU-cache friendly. In practice, this frequently outperforms pointer-based structures.</li><li><strong>Value semantics + Copy-on-Write (CoW): </strong>Copies are cheap until you mutate; when you do, Swift may allocate a new buffer. This is usually a win for typical stack usage.</li><li><strong>Low per-element overhead: </strong>Just the element payload (plus the array header). No per-node objects or pointers.</li><li><strong>Practical tips in Swift: </strong>Prefer append(_:) and removeLast() for stack ops. Call reserveCapacity(_:) if you can estimate size to minimize growth events.</li></ul><h4><strong>Trade-offs</strong></h4><ul><li>A rare resize costs O(n). If you’re pushing while capacity is full, a single operation can be “spiky”.</li><li>If you <em>must</em> push/pop at the <strong>front</strong>, array is a poor fit (shifts elements).</li></ul><h3>Singly Linked List</h3><ul><li><strong>True O(1) push/pop at the head: </strong>No resizes; just repoint the head.</li><li><strong>Flexible structural changes: </strong>Splicing, persistent (immutable) variants, or sharing sublists are natural.</li></ul><h4><strong>Trade-offs (especially in Swift)</strong></h4><ul><li><strong>Poor cache locality: </strong>Nodes are scattered; each access chases a pointer.</li><li><strong>ARC overhead: </strong>Each node is typically a reference type (or box), incurring retain/release on pushes/pops.</li><li><strong>Memory overhead: </strong>Per-node storage (next pointer + allocation header) increases footprint.</li><li><strong>No stdlib LinkedList: </strong>You’ll write/maintain your own, and performance is usually worse than Array for stack workloads.</li></ul><h3>Which one should you use for a stack in Swift?</h3><p><strong>Default to Array&lt;T&gt;</strong> for stacks in Swift/iOS.</p><p>You’ll get predictable <strong>amortized O(1)</strong> performance, better real-world throughput due to <strong>contiguous memory</strong>, and simpler code that plays well with Swift’s <strong>value semantics</strong> and <strong>CoW</strong>.</p><p><strong>Consider a Linked List</strong> only when:</p><ul><li>You specifically need <strong>structural sharing</strong> / persistent data structures, or</li><li>You need to <strong>splice</strong>/share prefixes frequently in a purely functional style, and you accept the runtime overhead, or</li><li>You’re in an academic/teaching context exploring pointer-based structures.</li></ul><blockquote><em>TL;DR: On iOS, the CPU cache and ARC costs make Array the pragmatic and faster stack backing in almost all app scenarios.</em></blockquote><h3>Implementing a Stack in Swift</h3><p>In the previous section, we discussed that stacks can be implemented using either arrays or linked lists. While both support constant-time push and pop under the right conditions, arrays in Swift are generally <strong>more performant</strong> due to their <strong>contiguous memory layout</strong>, <strong>cache efficiency</strong>, and <strong>low per-element overhead</strong>. For this reason, we will implement our stack using Array&lt;T&gt; .</p><pre>struct Stack&lt;Element&gt; {<br>    private var storage: [Element] = []<br><br>    // Utility<br>    var isEmpty: Bool { storage.isEmpty }<br><br>    var count: Int { storage.count }<br><br>    // Push: Add an element to the top<br>    mutating func push(_ element: Element) {<br>        storage.append(element)<br>    }<br>    // Pop: Remove and return the top element<br>    @discardableResult<br>    mutating func pop() -&gt; Element? {<br>        return storage.popLast()<br>    }<br><br>    // Peek: Look at the top element without removing it<br>    func peek() -&gt; Element? {<br>        return storage.last<br>    }<br>}</pre><p>This implementation leverages the standard library’s optimized <strong>Array</strong>, giving us amortized <strong>O(1)</strong> performance for both push(_ element:)(append) and pop() (popLast). With this foundation, you now have a <strong>generic stack</strong> you can reuse in your own Swift projects, whether for navigation, undo/redo mechanisms, or classic algorithms like DFS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*FvxCxqWKEL4XzG5_x5DKHw.png" /></figure><h3>Stacks in Practice: Navigation on iOS</h3><p>Stacks are not just an abstract data structure — they are the foundation of <strong>screen navigation</strong> in iOS apps. Every time you move forward into a new screen and then go back, you’re interacting with a stack managed by the system. Let’s take a look at a concrete example.</p><h4>UINavigationController</h4><p>In UIKit, navigation is powered by a <strong>stack of view controllers</strong>.</p><ul><li>pushViewController(_:animated:) → pushes a new screen onto the stack.</li><li>popViewController(animated:) → pops the top screen, revealing the one below.</li></ul><p><strong>Example:</strong></p><pre>// Assume we start with a HomeViewController<br>let detailViewController = DetailViewController()<br>navigationController?.pushViewController(detailViewController, animated: true)<br><br>// Later, to go back:<br>navigationController?.popViewController(animated: true)</pre><p>Here, the navigation controller maintains an internal stack:</p><pre>[HomeViewController]  // initial<br>[HomeViewController, DetailViewController]  // after push<br>[HomeViewController]  // after pop</pre><h4>SwiftUI’s NavigationStack</h4><p>In SwiftUI, starting with iOS 16, NavigationStack provides a declarative way to manage stacks of screens.</p><pre>struct ContentView: View {<br>    @State private var path: [Int] = []<br><br>    var body: some View {<br>        NavigationStack(path: $path) {<br>            List(0..&lt;5, id: \.self) { item in<br>                NavigationLink(&quot;Item \(item)&quot;, value: item)<br>            }<br>            .navigationDestination(for: Int.self) { value in<br>                Text(&quot;Detail for \(value)&quot;)<br>            }<br>        }<br>    }<br>}</pre><h4>Why This Matters</h4><ul><li>Thinking of navigation as a <strong>stack</strong> helps you reason about <strong>back navigation</strong> and how the system decides what screen to show.</li><li>It also connects directly with the theory: each new screen is a <strong>push</strong>, and every back action is a <strong>pop</strong>.</li></ul><h3>What You Need to Know for Your Interview</h3><p>Stacks are one of the most common data structures discussed in technical interviews. If you’re preparing for an iOS or general software engineering role, here’s what you should focus on:</p><h4>Core Concepts</h4><ul><li><strong>Definition</strong>: A stack is a LIFO (Last In, First Out) structure.</li><li><strong>Operations</strong>: Be ready to explain and implement push, pop, and peek.</li><li><strong>Complexity</strong>: push is O(1) amortized with arrays, O(1) with linked lists, pop is O(1) and peek is O(1).</li><li>Why “amortized” matters with arrays (resizing).</li></ul><h3>Implementation</h3><ul><li><strong>In Swift</strong>: Implement a generic Stack&lt;T&gt; using an array.</li><li><strong>Alternative</strong>: Show you understand how to implement it with a linked list, even if arrays are more common in iOS.</li></ul><blockquote><strong>Important note</strong>: In many interviews, it’s <strong>not necessary</strong> to build a stack from scratch. Interviewers often just want to see if you can work with the concept. Since Swift arrays already give you append and removeLast, you can use them directly to model stack behavior.</blockquote><h3>Real-World Applications</h3><p>Interviewers often test whether you can connect theory to practice. Be ready to explain:</p><ul><li><strong>Navigation controllers</strong>: how screens are pushed and popped.</li><li><strong>Undo/Redo</strong>: how stacks (often two of them) power these features.</li><li><strong>Expression evaluation</strong>: using stacks to parse mathematical expressions or validate parentheses.</li><li><strong>Backtracking</strong>: solving mazes, traversing trees, or DFS.</li></ul><h3>Common Interview Questions</h3><p>Some typical stack-related questions you’ll find in interviews (and on platforms like <strong>LeetCode</strong>):</p><ul><li><em>“Implement a stack in Swift.”</em></li><li><em>“Use a stack to validate balanced parentheses.”</em> — <a href="https://leetcode.com/problems/valid-parentheses/">LeetCode #20 — Valid Parentheses</a></li><li><em>“Evaluate a mathematical expression with operators and parentheses.”</em> — <a href="https://leetcode.com/problems/evaluate-reverse-polish-notation/">LeetCode #150 — Evaluate Reverse Polish Notation</a></li><li><em>“Design a stack that supports retrieving the minimum element in O(1).”</em> — <a href="https://leetcode.com/problems/min-stack/">LeetCode #155 — Min Stack</a></li><li><em>“Find the next greater element for each number in an array.”</em> — <a href="https://leetcode.com/problems/next-greater-element-i/">LeetCode #496 — Next Greater Element I</a></li><li><em>“Given daily temperatures, return how many days you’d have to wait for a warmer day.”</em> — <a href="https://leetcode.com/problems/daily-temperatures/">LeetCode #739 — Daily Temperatures</a></li><li><em>“Find the largest rectangle in a histogram.”</em> — <a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">LeetCode #84 — Largest Rectangle in Histogram</a></li><li><em>“Perform inorder traversal of a binary tree using a stack.”</em> — <a href="https://leetcode.com/problems/binary-tree-inorder-traversal/">LeetCode #94 — Binary Tree Inorder Traversal</a></li></ul><p>If you understand these concepts and can <strong>implement a stack quickly in Swift</strong>, you’ll be well prepared for data structure questions in your interview.</p><h3>Conclusion</h3><p>Stacks may look simple at first — just a data structure where the last element in is the first one out — but they are everywhere in iOS development. From the <strong>call stack</strong> that powers your Swift functions, to <strong>navigation controllers</strong> that push and pop screens, to <strong>undo/redo managers</strong>, stacks are a fundamental building block of how apps (and operating systems) work.</p><p>In this article, we explored stacks from theory to practice:</p><ul><li>The core <strong>LIFO principle</strong>.</li><li>How stacks appear <strong>behind the scenes in iOS</strong>.</li><li>Real-world <strong>analogies</strong> that make them intuitive.</li><li>A hands-on <strong>implementation in Swift</strong>.</li><li>And how to <strong>apply them in interviews</strong> and real development.</li></ul><p>The best way to truly understand stacks is to <strong>practice</strong> — try out the Swift implementation, play with UINavigationController or SwiftUI’s NavigationStack, and solve some classic problems on platforms like LeetCode.</p><h3><strong>Enjoyed this article?</strong></h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a4c2d02d1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’re Already Using Linked Lists in iOS with Swift — Here’s How]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/youre-already-using-linked-lists-in-ios-with-swift-here-s-how-bbe34d77a717?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbe34d77a717</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 22:26:03 GMT</pubDate>
            <atom:updated>2025-08-18T15:05:39.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Anaaq6YS1pX6Dsd8YmC2DA.png" /></figure><h3><em>You’re Already Using Linked Lists in iOS with Swift — Here’s How</em></h3><h4><em>Discover how the linked list data structure powers UIKit’s Responder Chain and learn to use it in your own Swift code.</em></h4><p>Even if you’ve never written a Linked List class in Swift, you’re probably already using this data structure every day when building iOS apps. Behind the scenes, UIKit relies on a form of linked list, the <strong>Responder Chain, </strong>to pass events from views to view controllers and beyond. In this article, we’ll explore what a linked list is, how it works in Swift, and uncover its hidden role inside UIKit. By the end, you’ll not only understand the theory but also know how to harness linked lists in your own Swift code.</p><h3>Why Linked Lists Exist</h3><p>In many cases, <strong>arrays</strong> are the go-to data structure in Swift due to their simplicity and constant-time (O(1)) access to elements by index. This preference is so strong that most of Apple’s frameworks are built around arrays as their primary collection type. For example:</p><ul><li><strong>UIKit</strong>’s UITableView and UICollectionView expect their data sources to be backed by arrays, with each cell corresponding to an item at a specific index.</li><li><strong>SwiftUI’s</strong>List and<strong> </strong>ForEach<strong> </strong>commonly work with arrays, where each element can be uniquely identified, making them straightforward to use and easy to integrate with dynamic data.</li><li>Even APIs like MapKit annotations or AVFoundation’s media tracks often return arrays for iteration and indexed access.</li></ul><p>This array-centric design makes them incredibly convenient for most app features, but it also exposes some well-known limitations when it comes to certain operations:</p><ul><li><strong>Insertion at the beginning</strong>: Adding an element at index 0 requires shifting all existing elements one position forward, resulting in a time complexity of <strong>O(N)</strong>.</li><li><strong>Expanding capacity</strong>: When an array’s storage needs to grow beyond its current capacity, a new memory block must be allocated and all elements copied over — another <strong>O(N)</strong> operation.</li><li><strong>Wasted space</strong>: Arrays often pre-allocate more space than currently needed, which can lead to unused memory until that capacity is filled.</li></ul><p>For certain types of problems, we need a data structure that:</p><ol><li>Allows <strong>fast insertions</strong> at the beginning or middle of the sequence.</li><li>Can <strong>grow and shrink dynamically</strong> without the need to reallocate memory for all elements.</li></ol><h3>Implementing a Simple Linked List in Swift</h3><p>A <strong>Linked List</strong> is made up of <strong>Nodes</strong>, where each node stores a value and a reference to the next node in the sequence.</p><p>Let’s start by defining a generic <strong>Node</strong> that can hold any type of value:</p><pre>final class Node&lt;T&gt; {<br>    var value: T<br>    var next: Node&lt;T&gt;?<br><br>    init(value: T, next: Node&lt;T&gt;? = nil) {<br>        self.value = value<br>        self.next = next<br>    }<br>}</pre><p>Here we have a value that holds the data of the node and next that points to the next node in the list (or nil if it’s the last node).</p><p>Now, let’s create our <strong>LinkedList</strong> class, which stores <strong>only the head</strong> of the list:</p><pre>final class LinkedList&lt;T&gt; {<br>    private var head: Node&lt;T&gt;?<br><br>    func addHead(_ value: T) { }<br><br>    func addTail(_ value: T) { }<br><br>    func insert(_ value: T, at position: Int) { }<br><br>    func getFirst() -&gt; T? { return nil }<br><br>    func getLast() -&gt; T? { return nil }<br><br>    func deleteHead() { }<br><br>    func deleteLast() { }<br><br>    func delete(at position: Int) { }<br><br>    func clear() { }<br><br>    func reverse() { }<br><br>    func printList() { }<br>}</pre><p>We’ll start with a <strong>minimal skeleton</strong> of a singly linked list in Swift that stores <strong>only a head reference</strong> (no tail). All methods are declared but intentionally left empty so we can implement them <strong>one by one</strong>, discussing the <strong>time and space complexity</strong> of each operation as we go. This layout makes trade‑offs explicit from the start without a tail pointer (we will explain that later). In the next sections, we’ll implement each method with concise reasoning and a clear complexity breakdown.</p><h4>Implementing addHead(_:)</h4><p>This method inserts a new element at the <strong>beginning</strong> of the linked list.</p><p>Since we store only the head reference, this is the <strong>fastest possible insertion</strong> in a singly linked list — we simply create a new node, point it to the current head, and then update the head to the new node.</p><pre>func addHead(_ value: T) {<br>    let newNode = Node(value: value, next: head)<br>    head = newNode<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>Create a new Node with the provided value.</li><li>Set its next pointer to the current head.</li><li>Update head to reference this new node.</li></ol><p><strong>Time Complexity: O(1)</strong> → no matter the list size, it takes the same number of operations.</p><p><strong>Space Complexity: O(1)</strong> → only a single new node is created.</p><h4>Implementing addTail(_:)</h4><p>Without a tail reference, adding an element at the <strong>end</strong> of the list requires <strong>traversing all nodes</strong> until we find the last one, then attaching the new node there.</p><pre>func addTail(_ value: T) {<br>    let newNode = Node(value: value)<br><br>    guard let currentHead = head else {<br>        head = newNode<br>        return<br>    }<br><br>    var current = currentHead<br>    while let next = current.next {<br>        current = next<br>    }<br>    current.next = newNode<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>Create a new Node with the provided value.</li><li>If the list is empty head == nil, set head to this node.</li><li>Otherwise, iterate from the head until we reach a node whose next is nil (the last node).</li><li>Set that node’s next to the new node.</li></ol><p><strong>Time Complexity: O(N)</strong> → we may need to traverse the entire list.</p><p><strong>Space Complexity: O(1)</strong> → only a single new node is created.</p><h4>Implementing insert(_:at:)</h4><p>This method inserts a new node at a <strong>specific position</strong> in the linked list, starting from index 0.</p><ul><li>If position == 0 , we can just call addHead(_:).</li><li>Otherwise, we traverse the list until we reach the node before the desired position, then adjust the pointers.</li><li>If the given position is greater than the current list length, no insertion will occur.</li></ul><pre>func insert(_ value: T, at position: Int) {<br>    guard position &gt;= 0 else { return }<br><br>    if position == 0 {<br>        addHead(value)<br>        return<br>    }<br><br>    var current = head<br>    var currentIndex = 0<br><br>    while current != nil &amp;&amp; currentIndex &lt; position - 1 {<br>        current = current?.next<br>        currentIndex += 1<br>    }<br><br>    guard let nodeBefore = current else { return }<br><br>    let newNode = Node(value: value, next: nodeBefore.next)<br>    nodeBefore.next = newNode<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>Validate that the position is non-negative.</li><li>If inserting at position <strong>0</strong>, reuse addHead(_:).</li><li>Traverse the list until reaching the node at index position — 1.</li><li>Create a new node, point it to the next node of nodeBefore.</li><li>Update nodeBefore.next to the new node.</li></ol><p><strong>Time Complexity: O(N)</strong> → traversal required until reaching the desired position.</p><p><strong>Space Complexity: O(1)</strong> → only one new node allocated.</p><h4>Implementing getFirst()</h4><p>This method returns the value stored in the <strong>first node</strong> of the linked list, or nil if the list is empty.</p><pre>func getFirst() -&gt; T? {<br>    return head?.value<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>If the list is empty head == nil, return nil.</li><li>Otherwise, return the value stored in the head node.</li></ol><p><strong>Time Complexity: O(1)</strong> → direct access to the head.</p><p><strong>Space Complexity: O(1)</strong> → no extra memory allocation.</p><h4>Implementing getLast()</h4><p>This method returns the value stored in the <strong>last node</strong> of the linked list, or nil if the list is empty.</p><p>Since we don’t store a tail reference, we must traverse the list from the head until we reach the node whose next is nil.</p><pre>func getLast() -&gt; T? {<br>    guard var current = head else { return nil }<br><br>    while let next = current.next {<br>        current = next<br>    }<br>    return current.value<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>If the list is empty (head == nil), return nil.</li><li>Start from the head node.</li><li>Move through the list until you find the node whose next is nil — that’s the last node.</li><li>Return the value stored in that node.</li></ol><p><strong>Time Complexity: O(N)</strong> → may require traversing the entire list.</p><p><strong>Space Complexity: O(1)</strong> → no extra memory allocation.</p><h4>Implementing deleteHead()</h4><p>This method removes the <strong>first node</strong> from the linked list.</p><p>We simply update head to point to the second node (if any), effectively discarding the first node.</p><pre>func deleteHead() {<br>    head = head?.next<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>If the list is empty head == nil, nothing happens.</li><li>Otherwise, set head to head?.next.</li><li>The old head is no longer referenced and will be deallocated automatically by Swift’s ARC.</li></ol><p><strong>Time Complexity: O(1)</strong> → constant time regardless of list size.</p><p><strong>Space Complexity: O(1)</strong> → no extra memory allocation.</p><h4>Implementing deleteLast()</h4><p>This method removes the <strong>last node</strong> from the linked list.</p><p>Since we don’t store a tail reference, we must traverse the list to find the <strong>second-to-last</strong> node, then set its next to nil.</p><pre>func deleteLast() {<br>    guard var current = head else { return }<br><br>    if current.next == nil {<br>        head = nil<br>        return<br>    }<br><br>    while let next = current.next, next.next != nil {<br>        current = next<br>    }<br><br>    current.next = nil<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>If the list is empty head == nil, do nothing.</li><li>If there’s only one node head.next == nil, set head to nil.</li><li>Otherwise, iterate until you find the node where next?.next is nil — that’s the second-to-last node.</li><li>Set its next to nil to remove the last node.</li></ol><p><strong>Time Complexity: O(N)</strong> → must traverse the list to find the second-to-last node.</p><p><strong>Space Complexity: O(1)</strong> → no extra memory allocation.</p><h4>Implementing delete(at:)</h4><p>This method removes the node at a <strong>specific position</strong> in the linked list.</p><ul><li>If the position is<strong> 0</strong>, it behaves like deleteHead().</li><li>Otherwise, we traverse the list until we reach the node just before the desired position, then adjust the pointers to skip the node being removed.</li></ul><pre>func delete(at position: Int) {<br>    guard position &gt;= 0, head != nil else { return }<br><br>    if position == 0 {<br>        deleteHead()<br>        return<br>    }<br><br>    var current = head<br>    var currentIndex = 0<br><br>    while current != nil &amp;&amp; currentIndex &lt; position - 1 {<br>        current = current?.next<br>        currentIndex += 1<br>    }<br><br>    guard let nodeBefore = current, nodeBefore.next != nil else { return }<br><br>    nodeBefore.next = nodeBefore.next?.next<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>If the position is negative or the list is empty, do nothing.</li><li>If position == 0, reuse deleteHead().</li><li>Traverse the list until you reach index position — 1.</li><li>If that node exists and has a next, adjust its next to skip over the node being deleted.</li></ol><p><strong>Time Complexity: O(N)</strong> → may require traversing most of the list.</p><p><strong>Space Complexity: O(1)</strong> → no extra memory allocation.</p><h4>Implementing clear()</h4><p>This method removes <strong>all nodes</strong> from the linked list.</p><p>We can simply set head to nil, allowing Swift’s ARC to deallocate the nodes automatically.</p><pre>func clear() {<br>    head = nil<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>Set head to nil.</li><li>Since no nodes are referenced anymore, ARC will clean them up.</li></ol><p><strong>Time Complexity: O(1)</strong> → regardless of list size, it’s a single assignment.</p><p><strong>Space Complexity: O(1)</strong> → no extra memory allocation.</p><h4>Implementing reverse()</h4><p>This method reverses the linked list <strong>in place</strong>, so the first node becomes the last and vice versa.</p><p>We iterate through the list, reversing the direction of each next pointer until the end.</p><pre>func reverse() {<br>    var previous: Node&lt;T&gt;? = nil<br>    var current = head<br>    var next: Node&lt;T&gt;? = nil<br><br>    while current != nil {<br>        next = current?.next<br>        current?.next = previous<br>        previous = current<br>        current = next<br>    }<br><br>    head = previous<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>Keep track of three references: previous, current, and next.</li><li>Iterate over the list:</li></ol><ul><li>Save the next node.</li><li>Reverse the current node’s next pointer to point to the previous node.</li><li>Move previous and current forward.</li></ul><p>3. At the end, set head to previous (the new first node).</p><p><strong>Time Complexity: O(N)</strong> → each node is visited exactly once.</p><p><strong>Space Complexity: O(1)</strong> → reversal is done in place, without extra data structures.</p><h4>Implementing printList()</h4><p>This method traverses the linked list from the head to the end, printing the value of each node.</p><pre>func printList() {<br>    var current = head<br>    while let node = current {<br>        print(node.value)<br>        current = node.next<br>    }<br>}</pre><p><strong>Step-by-step reasoning:</strong></p><ol><li>Start from the head.</li><li>While the current node is not nil:</li></ol><ul><li>Print its value.</li><li>Move to the next node.</li></ul><p><strong>Time Complexity: O(N)</strong> → each node is visited once.</p><p><strong>Space Complexity: O(1)</strong> → traversal uses only a single temporary variable.</p><p>With these methods in place, we now have a fully functional singly linked list in Swift that stores only a head reference. This structure supports insertions, deletions, lookups, and even in-place reversal, all while giving us predictable time and space complexities for each operation.</p><h3>Linked Lists in Everyday Life</h3><p>Learning a data structure is one thing — recognizing it in action is another. Linked lists appear in more places than you might expect, from iOS frameworks to everyday systems like public transportation.</p><h4>1. In the iOS World: The Responder Chain</h4><p>In UIKit, event handling uses a structure remarkably similar to a linked list: the <strong>Responder Chain</strong>.</p><p>Every object that inherits from UIResponder (such as UIView, UIViewController, or UIWindow) has a next property that points to the next responder in the sequence.</p><p>When an event occurs — a touch, key press, or action — UIKit passes it to the first responder. If that object doesn’t handle it, the event moves to the next responder, and so on, until either it’s handled or the chain ends.</p><p>This chain of UIResponder objects works essentially like a singly linked list, where:</p><ul><li>Each node is a UIResponder.</li><li>The next pointer references the next node in the chain.</li><li>Traversal continues sequentially until the event is resolved.</li></ul><p>Example from Apple’s documentation:</p><p>If a UIView inside a UIViewController receives an event it cannot handle, it forwards the event to its <strong>next responder</strong>, the UIViewController. If that controller can’t handle it either, the event moves to the UIWindow, and then to the UIApplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIdBTQ9YCyVjg1cFoxmESQ.png" /></figure><h4>2. In the Real World: A Subway Line</h4><p>Linked lists are also present in physical systems — the São Paulo Metrô map is a perfect analogy.</p><p>Think of each station as a <strong>node</strong> and the railway connecting to the next station as the <strong>pointer</strong>.</p><p>For example, in <strong>Line 1 — Blue</strong>, starting at Jabaquara (the head), the train stops at Conceição, then São Judas, then Saúde, and so on, until it reaches Tucuruvi (the tail).</p><ul><li><strong>Traversal:</strong> You can only move from one station to the next following the sequence — unlike an array, you can’t directly “jump” to station 10 without passing through all the stations before it.</li><li><strong>Insertion:</strong> Adding a new station between two existing ones is like inserting a new node in the middle of a linked list — you update the “pointers” so trains go through it in the right order.</li><li><strong>Deletion:</strong> Closing a station permanently means reconnecting the previous station’s “pointer” to skip over it.</li></ul><p>This analogy helps visualize how linked lists work — whether the “nodes” are objects in memory or subway stations in the city, the principle is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOng28HMUSnc-PHHdGW3Vw.png" /></figure><h3>Linked Lists vs Arrays: Pros and Cons</h3><p>Choosing between a linked list and an array isn’t about which one is “better” — it’s about picking the right tool for the job. Both have strengths and trade-offs that matter depending on the problem you’re solving.</p><h4>Linked Lists: Strengths</h4><ul><li><strong>Fast insertions/removals at the head or middle</strong> — Inserting or deleting a node doesn’t require shifting all elements; just update a few pointers (<strong>O(1)</strong> for head operations).</li><li><strong>Dynamic size</strong> — Can grow or shrink without reallocating a contiguous block of memory.</li><li><strong>No wasted capacity</strong> — Only allocate memory for elements that actually exist.</li></ul><h3>Linked Lists: Limitations</h3><ul><li><strong>Slow indexed access</strong> — Finding the nth element requires traversing from the head each time (<strong>O(N)</strong>).</li><li><strong>Extra memory overhead</strong> — Each node stores a value <strong>and</strong> a pointer to the next node.</li><li><strong>Cache inefficiency</strong> — Non-contiguous memory can hurt performance due to CPU cache misses.</li></ul><h3>Arrays: Strengths</h3><ul><li><strong>Fast random access</strong> — Accessing any index is <strong>O(1)</strong> thanks to contiguous memory storage.</li><li><strong>Cache-friendly</strong> — Elements stored together in memory improve CPU cache performance.</li><li><strong>Simpler structure</strong> — No extra memory for pointers; direct indexing is straightforward.</li></ul><h3>Arrays: Limitations</h3><ul><li><strong>Costly insertions/removals in the middle or at the start</strong> — Requires shifting elements (<strong>O(N)</strong>).</li><li><strong>Resizing overhead</strong> — Growing beyond capacity requires allocating a new block and copying all elements (<strong>O(N)</strong>).</li><li><strong>Wasted space</strong> — Often over-allocates memory to accommodate growth.</li></ul><p><strong>In short:</strong></p><ul><li>Use <strong>linked lists</strong> when you need frequent insertions/removals and rarely access elements by index.</li><li>Use <strong>arrays</strong> when you need fast, frequent indexed access and minimal memory overhead.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R41vishQTmul3f10GBh97w.png" /></figure><h3>Conclusion</h3><p>Linked lists are more than just a computer science exercise — they’re a versatile tool that appear in real-world systems and even in the frameworks we use daily in iOS development. While arrays remain the default choice in many situations, understanding the trade-offs between these two structures allows you to make informed decisions and write more efficient, maintainable code.</p><h3>Next Steps</h3><p>In the next article, we’ll explore <strong>linked list variations</strong> and how they can impact performance and use cases:</p><ul><li><strong>Tail references</strong> — How storing the last node can reduce certain operations from <strong>O(N)</strong> to <strong>O(1)</strong>.</li><li><strong>Singly vs Doubly Linked Lists</strong> — Trade-offs between memory usage and traversal flexibility.</li><li><strong>Circular Linked Lists</strong> — When wrapping around the end makes sense.</li><li><strong>Linked Lists in Queues</strong> — Why they’re a natural fit for FIFO structures.</li></ul><p>If you’re interested in going deeper into algorithms and performance, I’ve written related articles:</p><ul><li><a href="https://medium.com/@luizfernandosalvaterra/understanding-big-o-in-swift-cc697905e13b">Understanding Big O in Swift</a></li><li><a href="https://medium.com/@luizfernandosalvaterra/why-algorithms-matter-exploring-swift-with-search-examples-0fdb0cb2c1ad">Why Algorithms Matter: Exploring Swift with Search Examples</a></li></ul><h3>References</h3><ul><li><a href="https://developer.apple.com/documentation/uikit/using-responders-and-the-responder-chain-to-handle-events">Apple Documentation: Using Responders and the Responder Chain to Handle Events</a></li><li><a href="https://www.geeksforgeeks.org/dsa/linked-list-data-structure/">Linked Lists: Deep Dive</a></li></ul><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbe34d77a717" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching LLMs to Act: Mastering Tool Calling in FoundationModels]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/teaching-llms-to-act-mastering-tool-calling-in-foundationmodels-9bf319c081b2?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bf319c081b2</guid>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 00:56:30 GMT</pubDate>
            <atom:updated>2025-08-18T15:02:38.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*00keuaRBUWuQnxZCj1yT0Q@2x.png" /></figure><h4><strong>Building On-Device AI Agents with Tool Calling using Swift</strong></h4><h3>Introduction</h3><p>Welcome to the <strong>final article</strong> in our <a href="https://medium.com/@luizfernandosalvaterra/exploring-apple-foundationmodels-privacy-first-ai-on-your-device-a7deac7719fc"><strong>FoundationModels</strong></a> series.</p><p>We began with <a href="https://medium.com/@luizfernandosalvaterra/inside-foundationmodels-how-sessions-actually-work-1a250bb30110"><strong>Sessions</strong></a>, the heart — the component responsible for memory, context, and stateful interactions. Then we explored <a href="https://medium.com/@luizfernandosalvaterra/guided-generation-with-foundationmodels-how-to-get-swift-structs-from-llms-ad663e60d716"><strong>Guided Generation</strong></a>, the brain — enabling the model to speak fluent Swift with structured outputs.</p><p>Now, we arrive at the final piece: <strong>tool calling</strong>.</p><p>With <strong>Tool Calling</strong>, FoundationModels evolve from understanding and structuring — to <strong>acting with intent</strong>. The model can now trigger real Swift functions directly on-device, making decisions and executing logic based on natural language prompts. It’s a powerful step toward <strong>local intelligent agents</strong> — all private, fast, and offline.</p><p>In this article, we’ll dive into how Tool Calling works, how to define and register tools, how the model decides what to call, and what you can build with this new capability.</p><p>Let’s close this trilogy by teaching our LLM how to act.</p><h3>What is Tool Calling?</h3><p>Tool Calling is the missing link between natural language and real-world action.</p><p>In the world of cloud-based LLMs like <strong>GPT</strong> and <strong>Claude</strong>, developers use what’s called the <strong>Model Context Protocol (MCP)</strong> — a system that lets language models invoke external tools, APIs, and structured functions by describing them in a special schema. With MCPs, the model doesn’t just respond — it <strong>decides</strong> when to act and how to call those tools with the right inputs.</p><p>Apple’s <strong>Tool Calling</strong> follows a similar design philosophy — but with a critical twist:</p><blockquote><em>It all runs </em><strong><em>on-device</em></strong><em>, in </em><strong><em>Swift</em></strong><em>, and with </em><strong><em>full privacy</em></strong><em>.</em></blockquote><p>With Tool Calling, you expose real Swift functions to the model using a simple protocol Tool. The FoundationModel can:</p><ul><li>Understand user intent from natural language</li><li>Match it to a Swift function you’ve defined</li><li>Parse the arguments</li><li>Call the function asynchronously</li><li>And use the result to continue the conversation</li></ul><p>It’s a <strong>local, private, Apple-native</strong> version of the same paradigm driving AI agents in the cloud — now accessible on your iPhone, iPad, or Mac.</p><p>Just like MCPs empower GPT and Claude to <strong>connect understanding with action</strong>,</p><p><strong>Tool Calling lets FoundationModels on Apple devices do the same — securely, offline, and instantly.</strong></p><h4>Understanding the Tool Protocol</h4><p>Here is the raw protocol definition for Tool, as available in the <strong>FoundationModels</strong> framework:</p><pre>@available(iOS 26.0, macOS 26.0, *)<br>@available(tvOS, unavailable)<br>@available(watchOS, unavailable)<br>public protocol Tool&lt;Arguments, Output&gt; : Sendable {<br>    associatedtype Output : PromptRepresentable<br>    associatedtype Arguments : ConvertibleFromGeneratedContent<br><br>    var name: String { get }<br>    var description: String { get }<br>    var parameters: GenerationSchema { get }<br>    var includesSchemaInInstructions: Bool { get }<br><br>    func call(arguments: Self.Arguments) async throws -&gt; Self.Output<br>}</pre><h4>What Each Part Means</h4><p>Let’s break it down, line by line:</p><ul><li><strong>associatedtype Output : PromptRepresentable: </strong>This defines the return type of the tool. It must be convertible to something the model can reason about, such as a String or a Generable struct.</li><li><strong>associatedtype Arguments : ConvertibleFromGeneratedContent: </strong>This defines the input the model must generate to invoke your tool. It usually maps to a @Generable struct or GeneratedContent.</li><li><strong>var name: String: </strong>A unique identifier for the tool. Think of it like “get_weather” or “search_contacts” — this is used internally and injected into the model’s context.</li><li><strong>var description: String: </strong>A natural language explanation of what the tool does. This is exposed to the model to help it decide when and why to use it.</li><li><strong>var parameters: GenerationSchema: </strong>This schema describes what arguments the tool expects. In most use cases, the framework will generate this for you based on the Arguments type.</li><li><strong>var includesSchemaInInstructions: Bool: </strong>Controls whether the tool’s metadata (name, description, schema) is injected into the model’s instructions. The default is true. You can set it to false if the model already “knows” how to use the tool (e.g., fine-tuned behavior).</li><li><strong>func call(arguments: Self.Arguments) async throws -&gt; Self.Output: </strong>The actual Swift function to execute when the model chooses to invoke the tool. It’s asynchronous and can throw. Any errors here will be wrapped and surfaced to the session.</li></ul><h3>Defining a Tool</h3><p>In <strong>FoundationModels</strong>, tools are Swift functions that the model can invoke when it recognizes a matching intent in natural language. To make a function “callable,” you define it as a Swift type conforming to the Tool protocol you just saw.</p><p>A tool is made up of three key parts:</p><ol><li><strong>The Tool Type</strong></li><li><strong>Arguments</strong></li><li><strong>The Call Logic</strong></li></ol><h4>Conforming to Tool</h4><p>To define a tool, create a struct that conforms to Tool. You’ll need to:</p><ul><li>Provide a name and a description</li><li>Define an Arguments struct that conforms to @Generable with @Guide for improved intent mapping</li><li>Implement an async call(arguments:) function that returns a <strong>String</strong> or other @Generable output.</li></ul><h4>Example: Simple Search Food Tool</h4><pre>struct SearchFoodTool: Tool {<br>    let name = &quot;search_food_tool&quot;<br>    let description = &quot;Searches a local database for food recipes.&quot;<br><br>    @Generable<br>    struct Recipe {<br>        var name: String<br>        var description: String<br>        var link: String<br>    }<br><br>    @Generable<br>    struct Arguments {<br>        @Guide(description: &quot;The type of food to search for&quot;)<br>        var searchTerm: String<br>        @Guide(description: &quot;The number of recipes to get&quot;, .range(1...6))<br>        var limit: Int<br>    }<br>    <br>    func call(arguments: Arguments) async throws -&gt; [Recipe] {<br>        let recipes = try await RecipeService.getRecipes(searchTerm: arguments.searchTerm)<br>        return recipes<br>    }<br>}</pre><h4>Tips:</h4><ul><li><strong>Use descriptive names</strong> so the model can match user input accurately.</li><li><strong>Arguments</strong> must be @Generable, which allows <strong>FoundationModels</strong> to parse natural language into structured values.</li><li>If you want more control over how the model interprets arguments, you can use the @Guide annotation.</li></ul><p>This is all you need to make your first tool — a native Swift function, callable from natural language prompts. Next, we’ll look at how to register it into a session and let the model discover and use it.</p><h3>Registering Tools in a Session</h3><p>Once you’ve defined a tool, the next step is registering it into a session. Tool registration is how the model becomes aware of which functions it can potentially call during natural language generation.</p><p>With <strong>FoundationModels</strong>, this step is remarkably simple. You just pass your tool instances into the tools: parameter when creating a LanguageModelSession. Optionally, you can provide behavioral instructions to guide the model’s personality and decision-making.</p><pre>let session = LanguageModelSession(<br>    tools: [SearchFoodTool()],<br>    instructions: &quot;You are a helpful assistant that knows how to find food information.&quot;<br>)</pre><p>That’s it — your session is now fully equipped to interpret prompts, decide when to invoke tools, and execute them with the appropriate arguments.</p><h3>Triggering Tool Calls from Natural Language</h3><p>Once you’ve registered your tools inside a LanguageModelSession, triggering them becomes surprisingly natural — literally.</p><p>You don’t need to manually call any function or pass arguments. Instead, you write prompts as if you were talking to a human assistant, and the model decides <em>if</em> and <em>how</em> to invoke your tool behind the scenes.</p><pre> let response = try await session.respond(<br>    to: &quot;Find me a good piza recipe&quot;<br> )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X57vJEu4lZmzc19iEsIr6Q.png" /></figure><p>The model understood the intent and triggered the correct tool call. The response returned a friendly, contextual message — complete with a recipe summary and a link:</p><blockquote><em>“I found a great recipe for Homemade Pizza Margherita…”</em></blockquote><p>This demonstrates how robust the <strong>FoundationModels’ Tool Calling</strong> is. Even with informal phrasing or small errors, the model is still capable of:</p><ul><li>Understanding the user’s intent</li><li>Selecting the appropriate tool (e.g., SearchFoodTool)</li><li>Automatically generating valid arguments</li><li>Calling the Swift function</li><li>Using the result as part of its natural response</li></ul><h4>What’s Really Happening Behind the Scenes</h4><p>Here’s what happens in the background when you call respond(to:):</p><ol><li><strong>Intent Detection: </strong>The model processes the prompt and determines that it aligns with a registered tool.</li><li><strong>Argument Inference: </strong>It generates the correct arguments using the schema defined in your tool (e.g., count: 1).</li><li><strong>Function Execution: </strong>Your Swift tool’s call(arguments:) runs asynchronously.</li><li><strong>Response Composition: </strong>The output is then incorporated naturally into the model’s response.</li></ol><p>All of this feels like magic — but it’s just <strong>FoundationModels</strong> combining structured understanding with action.</p><h4>Why This Matters</h4><p>Unlike traditional keyword-based systems, this allows developers to build <strong>semantic interfaces</strong> where natural language drives real Swift logic. And since it’s all on-device, it’s fast, private, and reactive — no server round-trips required.</p><h3>Tool Calling Runs Concurrently — Make It Thread-Safe</h3><p>When a <strong>FoundationModel</strong> decides to call your tool, it doesn’t do so in a single-threaded environment. In fact, tool calls may run <strong>concurrently</strong>, especially if:</p><ul><li>The model tries to evaluate multiple candidate tools in parallel.</li><li>Your session includes multiple tools that could be called in sequence or branching logic.</li><li>You’re streaming or responding to long-form or multi-part prompts.</li></ul><p>This means your tool’s call(arguments:) function <strong>can</strong> be executed:</p><ul><li>Multiple times at once.</li><li>Interleaved with other tools.</li><li>In parallel with other model operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*JIHDNakla8onpDBiu8Byow.png" /></figure><h4>The Tool Protocol Requires Sendable</h4><p>The native Tool protocol enforces this by requiring both the tool and its types to conform to Sendable, ensuring compatibility with Swift concurrency:</p><pre>public protocol Tool&lt;Arguments, Output&gt;: Sendable {<br>    ...<br>    func call(arguments: Arguments) async throws -&gt; Output<br>}</pre><blockquote><em>This is a strong constraint enforced by the protocol: your tools must be thread-safe.</em></blockquote><h3>Limitations and Best Practices</h3><p>While Tool Calling in <strong>FoundationModels</strong> is powerful, it’s not foolproof. To get reliable and consistent results, you need to understand how the model interprets your tools — and design accordingly.</p><h4>It’s All About the Prompt</h4><p>Unlike traditional function calls, the model decides <strong>when</strong> and <strong>how</strong> to invoke a tool based entirely on:</p><ul><li>The <strong>natural language prompt</strong></li><li>The <strong>tool’s name and description</strong></li><li>The <strong>provided schema</strong>, including argument types and guides</li></ul><p>This means that tool triggering is probabilistic and <strong>highly sensitive to phrasing and structure</strong>.</p><h4>Common Pitfalls</h4><p>The model <strong>might ignore a tool</strong> if:</p><ul><li>The tool name is too abstract or unclear</li><li>The prompt doesn’t closely match the tool description</li><li>The instructions are too vague or missing</li></ul><p>Even when triggered, the model might:</p><ul><li>Skip required arguments</li><li>Misinterpret types or expected formats</li><li>Generate invalid values outside your expected range</li></ul><h4>Strategies to Improve Accuracy</h4><ul><li><strong>Use clear, action-oriented names</strong> for your tools (e.g., searchFood, getWeather, createReminder)</li><li><strong>Write descriptions like you’re talking to a junior developer</strong>: clear, imperative, and task-specific</li><li><strong>Add explicit guides</strong> @Guide on tool arguments when you expect structure or limits</li><li><strong>Provide a good session instruction</strong> to steer the model’s behavior (e.g., <em>“You are a helpful assistant that knows how to find food information.”</em>)</li></ul><h3>Conclusion</h3><p>With Tool Calling, FoundationModels reach a new level of capability: they can now <strong>observe</strong>, <strong>reason</strong>, and <strong>act</strong> — all locally, securely, and privately.</p><p>You’re no longer limited to parsing text or guessing intent. Your models can:</p><ul><li>Understand natural language</li><li>Map it to real Swift functions</li><li>Execute those functions</li><li>And continue the conversation based on actual results</li></ul><p>This unlocks the door to building <strong>on-device agents</strong> that aren’t just reactive, but interactive. Assistants that book meetings, search local data, or control your app logic — all without ever leaving the user’s device.</p><p>And with that, we’ve reached the end of our journey through the <strong>FoundationModels</strong> series. From understanding how <strong>Sessions</strong> manage context, to structuring output with <strong>Guided Generation</strong>, and now enabling real-world actions with <strong>Tool Calling</strong> — you now have the building blocks to create powerful, private, on-device AI experiences with Swift.</p><p>Now it’s your turn:</p><p><strong>Explore. Break things. Prototype wildly.</strong></p><p>FoundationModels give you the tools — the rest is up to you.</p><h3>Useful Links</h3><ul><li><a href="https://medium.com/@luizfernandosalvaterra/exploring-apple-foundationmodels-privacy-first-ai-on-your-device-a7deac7719fc">Exploring Apple FoundationModels: Privacy-First AI on Your Device</a></li><li><a href="https://medium.com/@luizfernandosalvaterra/inside-foundationmodels-how-sessions-actually-work-1a250bb30110">Inside FoundationModels: How Sessions Actually Work</a></li><li><a href="https://medium.com/@luizfernandosalvaterra/guided-generation-with-foundationmodels-how-to-get-swift-structs-from-llms-ad663e60d716">Guided Generation with FoundationModels: How to Get Swift Structs from LLMs</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2025/286">WWDC 2025: Meet Foundation Models</a></li><li><a href="https://developer.apple.com/documentation/FoundationModels?changes=_10_5">FoundationModels Documentation (Beta)</a></li></ul><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bf319c081b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guided Generation with FoundationModels: How to Get Swift Structs from LLMs]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/guided-generation-with-foundationmodels-how-to-get-swift-structs-from-llms-ad663e60d716?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad663e60d716</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 23:32:04 GMT</pubDate>
            <atom:updated>2025-08-18T15:00:40.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*00keuaRBUWuQnxZCj1yT0Q@2x.png" /></figure><h4>Teaching Your LLM What to Say — and How to Say It</h4><h3>Introduction</h3><p>Over the past two articles, we’ve explored how Apple’s new <strong>FoundationModels</strong> framework brings Large Language Models (LLMs) directly to your device — enabling private, fast, and session-aware AI interactions entirely on Apple Silicon.</p><p>But so far, we’ve been working with <strong>plain text</strong> responses. And if you’ve ever tried to parse natural language into app logic, you know how fragile and error-prone that can be.</p><p>What if your LLM could speak Swift? What if it could <strong>directly return a struct</strong>, a model, or a type-safe object — instead of a string you have to clean and parse?</p><p>That’s exactly what <strong>Guided Generation</strong> unlocks.</p><p>In this article of the series, we’ll explore how to:</p><ul><li>Define Swift types that your LLM can generate</li><li>Use GuidedGenerationRequest to request structured responses</li><li>Handle generation results safely and predictably</li><li>Combine instructions + guidance for precise, reliable output</li></ul><p>Let’s move beyond free-form text and start writing AI that knows exactly what you need — in code.</p><h3>Why Structured Output Matters</h3><p>Working with raw natural language can feel like wrestling spaghetti: flexible, expressive — but also unpredictable. That’s fine for chatbots or storytelling. But when your app needs reliable, parsable data, <strong>free-form text just doesn’t cut it</strong>.</p><p>That’s where <strong>Guided Generation</strong> shines: instead of manually parsing data and praying for consistency, you get actual Swift types back — fully validated, strongly typed, and ready to use in your UI, logic, or storage.</p><h4>The JSON Approach (Fragile &amp; Frustrating)</h4><pre>struct Recipe: Decodable {<br>    let name: String<br>    let description: String<br>}<br><br>let session = LanguageModelSession()<br>let response = try await session.respond(to: &quot;Give me a JSON with a name and description for a dessert recipe.&quot;)<br><br>let text = response.content<br>let data = text.data(using: .utf8)!<br><br>let decoded = try? JSONDecoder().decode(Recipe.self, from: data)</pre><p>What could go wrong?</p><ul><li>The model might skip quotes, use ‘ instead of “, or forget the {} altogether.</li><li>Even if it <em>looks</em> like JSON, subtle issues (like trailing commas or typos) break decoding.</li><li>You’ll need manual sanitization or regex fixes — and suddenly your clean Swift code is a mess of edge cases.</li></ul><h4>The Swift Way: @Generable</h4><p>Enter <strong>Guided Generation</strong> — Apple’s way of letting LLMs speak Swift natively.</p><pre>@Generable<br>struct Recipe {<br>    let name: String<br>    let description: String<br>}<br><br>let session = LanguageModelSession()<br>let response = try await session.respond(<br>    to: &quot;Suggest a dessert recipe&quot;,<br>    generating: Recipe.self<br>)<br><br>let recipe: Recipe = response.content<br>print(recipe.name)<br>print(recipe.description)</pre><p>No JSON. No decoding. You get your struct, already populated, fully type-checked and ready to use.</p><h4>Why It’s Game-Changing</h4><ul><li>It works with any <strong>Codable</strong> Swift type.</li><li>No need to teach the model how JSON works — it figures it out under the hood.</li><li>If it fails, you get .partial or .failure with structured error handling.</li></ul><p>And here’s the <strong>killer feature</strong>:</p><blockquote><em>The model generates properties from </em><strong><em>top to bottom</em></strong><em>, one by one.</em></blockquote><p>That means you can stream results as they arrive — and update your UI <strong>in real-time</strong>:</p><pre>let stream = session.streamResponse(to: prompt, generating: Recipe.self)<br><br>for try await partial in stream {<br>    if let name = partial.name {<br>        nameLabel.text = name<br>    }<br>    if let description = partial.description {<br>        descriptionLabel.text = description<br>    }<br>}</pre><p>This makes Guided Generation <strong>perfect for SwiftUI previews</strong>, async forms, and any app where immediacy matters.</p><h3>Steering the Model with @Guide</h3><p>Once your type is @Generable, the next step is to fine-tune how each field is generated. That’s where @Guide comes in — allowing you to describe what each property means, constrain values, and steer the language model’s behavior with natural-language metadata.</p><p>This not only increases reliability — it also unlocks more complex types like enums, arrays, and nested models.</p><h4>How @Guide Works</h4><p>Each @Guide acts like a mini prompt attached to a property. It tells the model:</p><ul><li><strong>What the field represents</strong></li><li><strong>What format to use</strong></li><li><strong>What constraints exist</strong> (e.g. a range, list of values, or any value from a given list)</li></ul><p>You can apply <strong>@Guide</strong> to:</p><ul><li>String, Int, Double, Bool</li><li>Arrays of any type</li><li>Enums</li><li>Nested <strong>@Generable</strong> types</li></ul><h4>.constant(…): Locking a Field to a Fixed Value</h4><p>If you want the model to always generate a fixed value for a property, use .constant(…). This is great for setting defaults or enforcing consistency.</p><pre>  @Generable<br>struct LegalDisclaimer {<br>    @Guide(description: &quot;Static legal footer&quot;, .constant(&quot;All rights reserved.&quot;))<br>    var footer: String<br>}</pre><blockquote>Use for fixed values — perfect for testing, templates, or hard-coded scenarios like “destination”: “Japan”.</blockquote><p>This guarantees that footer will always return <strong>“All rights reserved.”</strong>, regardless of prompt context.</p><h4>.range(…): Enforcing a Valid Numeric Range</h4><p>Use .range(…) to ensure the model generates a <strong>value within a specific numeric range</strong>. The bounds are <strong>inclusive</strong>, and this guide applies to numeric properties like Int, Double, and Decimal.</p><p>It’s not a soft suggestion — the model will attempt to produce values strictly <strong>within</strong> the defined range.</p><pre>@Generable<br>struct GameCharacter {<br>    @Guide(description: &quot;Character level&quot;, .range(1...100))<br>    var level: Int<br>}</pre><p>In this case, the generated level will always be between <strong>1 and 100</strong>, inclusive. If the model generates something outside of this range, decoding will <strong>fail</strong> or return a .partial result.</p><p>You should use .range(...) when you need to ensure that a numeric property stays within a specific, valid interval. It’s ideal for cases where values must fall within defined limits — such as character levels (e.g., 1–100), percentages (0–100), price ranges, or rating scores. This guide enforces boundaries and helps avoid unexpected or invalid outputs from the model.</p><blockquote>Best for numbers that represent bounded inputs like levels, scores, or ratings.</blockquote><h4>.minimum(…) and .maximum(…): Controlling Numeric Ranges</h4><p>Use .minimum(...) and .maximum(...) to constrain numeric values — ideal for things like pricing, ratings, or counts.</p><pre>@Generable<br>struct Rating {<br>    @Guide(description: &quot;User score from 1 to 5&quot;, .minimum(1), .maximum(5))<br>    var score: Int<br>}</pre><blockquote>Use when your range is open-ended — e.g., prices above a threshold, or minimum valid scores. <em>Great for Decimal values like prices or weights.</em></blockquote><h4>Arrays and .count(…): Fixed Number of Items</h4><p>When you want an array with a specific number of items, use .count(...).</p><pre>@Generable<br>struct LunchMenu {<br>    @Guide(description: &quot;Exactly three items for the lunch special&quot;, .count(3))<br>    var items: [String]<br>}</pre><blockquote>Enforce exact size on arrays. Perfect for “top N” lists or when your UI has limited space (e.g., top 3 goals).</blockquote><h4>.minimumCount(…) and .maximumCount(…): Flexible Array Bounds</h4><p>To allow a variable number of items, but within bounds, use:</p><pre>@Generable<br>struct GroceryList {<br>    @Guide(description: &quot;At least 2 items&quot;, .minimumCount(2))<br>    var items: [String]<br>}</pre><pre>@Generable<br>struct TravelChecklist {<br>    @Guide(description: &quot;Up to 10 checklist items&quot;, .maximumCount(10))<br>    var items: [String]<br>}</pre><blockquote>Control list size dynamically. Useful for optional lists or validating response verbosity (e.g., 1–5 suggestions).</blockquote><h4>.anyOf([…]): Restricting Valid Values (Soft Enum Behavior)</h4><p>If a field should only accept certain strings, use .anyOf([...]). This simulates enum-like constraints for string properties:</p><pre>@Generable<br>struct WeatherPreferences {<br>    @Guide(description: &quot;Preferred temperature unit&quot;, .anyOf([&quot;Celsius&quot;, &quot;Fahrenheit&quot;]))<br>    var unit: String<br>}</pre><blockquote>Simulate enums for String properties. Great for things like moods, regions, or units of measure. <em>Also ensures consistent values the model can “choose from”.</em></blockquote><p>The @Guide annotations are your primary tool for shaping how the model generates structured output. By thoughtfully applying constraints like .range, .constant, .anyOf, and array count modifiers, you can significantly increase the reliability and relevance of the model’s responses. These guides help you align model behavior with your app’s expectations — enabling structured, validated content with minimal post-processing. As we’ll see in the next section, understanding how to interpret the model’s output is just as important as guiding its input.</p><h3>respond() vs streamResponse(): Choosing the Right Tool for UX</h3><p><strong>FoundationModels</strong> provides two powerful ways to generate @Generable Swift types:</p><ul><li>.respond(to:generating:)</li><li>.streamResponse(to:generating:)</li></ul><p>At first glance, they seem similar — both produce strongly-typed Swift objects — but they differ fundamentally in <strong>how</strong>and <strong>when</strong> they deliver results.</p><h4>respond(to:generating:) — All or Nothing</h4><p>This method performs the full generation and decoding <strong>before</strong> returning anything:</p><pre>let session = LanguageModelSession()<br>let result = try await session.respond(<br>    to: &quot;Plan a trip to Brazil.&quot;,<br>    generating: Trip.self<br>)</pre><p>You only get the result when the entire struct is generated and validated.</p><p>This makes it ideal for:</p><ul><li>Quick one-shot generations</li><li>Background processing</li><li>Unit testing or tools</li></ul><p>But in UI contexts, it may lead to a <strong>perceived delay</strong>, especially for more complex prompts.</p><h4>streamResponse(to:generating:) — Field-by-Field Streaming</h4><p>In contrast, streamResponse emits incremental updates <strong>as soon as each field is generated</strong>.</p><p>This enables a responsive, interactive experience in SwiftUI.</p><pre>for try await partial in session.streamResponse(<br>    to: &quot;Plan a trip to Brazil.&quot;,<br>    generating: Trip.self<br>) {<br>    print(&quot;Updated partial struct:&quot;, partial.result)<br>}</pre><p>Under the hood, the model fills the struct <strong>from top to bottom</strong>, one property at a time.</p><p>Each emitted PartiallyGenerated&lt;T&gt; contains a partially completed object that you can render immediately.</p><h4>Practical Example in SwiftUI</h4><p>Let’s say you’re generating a Trip struct and you want to update your <strong>SwiftUI</strong> state</p><p>By streaming the response, your UI can:</p><ul><li>Display cities as they arrive ([&quot;São Paulo&quot;, &quot;Rio de Janeiro&quot;]) → ([&quot;São Paulo&quot;, &quot;Rio de Janeiro&quot;, &quot;Salvador&quot;])</li><li>Show a “typing” animation for destination</li><li>Keep the user engaged while generation completes</li></ul><pre>@State var trip = Trip(cities: [], destination: &quot;&quot;)<br><br>Task {<br>    for try await partial in session.streamResponse(<br>        to: &quot;Plan a cultural trip to Brazil.&quot;,<br>        generating: Trip.self<br>    ) {<br>        trip = partial.result<br>    }<br>}</pre><p>You can even combine this with animations, progress indicators, or voice-over accessibility updates — just like a real-time assistant experience.</p><p>By choosing the right method based on context, you can shape user expectations and improve interactivity without compromising on privacy or performance.</p><h3>Limitations and Best Practices</h3><p>While Guided Generation with @Generable offers powerful structured output, it’s important to remember that you’re working with a relatively small on-device model — currently around <strong>3 billion parameters</strong>. This compact size ensures fast, private, and offline execution, but introduces a few limitations you should account for.</p><h4>Common Limitations</h4><ul><li><strong>Missing or incomplete fields: </strong>The model may skip properties or leave them blank, especially in larger structs or when the prompt is vague.</li><li><strong>Inconsistent data: </strong>Even with guides, the model can occasionally generate values outside expected bounds, particularly for nested arrays or optional fields.</li><li><strong>Semantic confusion: </strong>The model might confuse similar field names, especially when multiple string properties are present with overlapping descriptions.</li></ul><h4>Best Practices</h4><ul><li><strong>Simplify your types: </strong>Keep your @Generable structs flat and focused. Avoid deep nesting or too many properties at once.</li><li><strong>Guide clearly and explicitly: </strong>Combine @Guide modifiers like .count, .anyOf, and .range(...) to constrain the model’s possibilities and improve accuracy.</li><li><strong>Validate after generation: </strong>Always apply business logic checks after generation to catch inconsistencies or fallback to defaults.</li><li><strong>Break down your prompts: </strong>When targeting large objects, consider splitting generation into multiple steps or chained sessions. For example, generate a summary first, then a detailed breakdown.</li><li><strong>Retry on failure: </strong>If decoding fails or results don’t meet your criteria, retry with a slightly adjusted prompt or fallback instructions.</li></ul><h3>Conclusion</h3><p>Guided Generation marks a pivotal shift in how we interact with LLMs on Apple platforms. Instead of treating outputs as unstructured blobs of text, we now <strong>speak Swift directly to our models</strong> — and receive well-formed, typed responses in return.</p><p>This means:</p><ul><li>Less natural language parsing,</li><li>Fewer brittle string manipulations,</li><li>And more <strong>declarative, predictable, and safe AI output</strong>.</li></ul><p>In this article, you learned:</p><ul><li>Why structured output matters, and how it unlocks better UX</li><li>How to define generable Swift types with fine-tuned guides</li><li>The differences between .respond streamResponse — and when to use each</li><li>Techniques to handle decoding, control randomness, and deal with model limitations</li></ul><p>With these tools in hand, you’re not just using a model — you’re <strong>engineering its behavior</strong>.</p><p>And best of all? It runs entirely on your device.</p><p>If you’ve started experimenting with Guided Generation, I’d love to hear how you’re using it.</p><p>Feel free to <strong>comment, share your results</strong>, or suggest improvements!</p><h3>What’s Next</h3><p>We’ve now explored the power of structured output with Guided Generation — but we’re just scratching the surface of what <strong>FoundationModels</strong> can do.</p><p>Up next: <strong>Tool Calling.</strong></p><p>You’ll learn how to define functions Swift-side and let the model intelligently decide when (and how) to invoke them — unlocking dynamic, context-aware workflows that feel truly intelligent.</p><p>In the meantime:</p><ul><li>Try creating your own @Generable types</li><li>Experiment with streamResponse for responsive UIs</li><li>Push the limits of what the on-device 3B model can handle</li></ul><p>If you missed the previous articles:</p><ul><li><a href="https://medium.com/@luizfernandosalvaterra/exploring-apple-foundationmodels-privacy-first-ai-on-your-device-a7deac7719fc">Exploring Apple FoundationModels: Privacy-First AI on Your Device</a></li><li><a href="https://medium.com/@luizfernandosalvaterra/inside-foundationmodels-how-sessions-actually-work-1a250bb30110">Inside FoundationModels: How Sessions Actually Work</a></li></ul><p>This framework is still evolving — and so are these articles.</p><p>Feel free to leave feedback, share use cases, or reach out with questions.</p><p>As Apple expands its model lineup and capabilities, I’ll be updating and writing more to keep you ahead of the curve.</p><h3>Links &amp; References</h3><ul><li><a href="https://developer.apple.com/documentation/FoundationModels?changes=_10_5">FoundationModels Documentation (Beta)</a></li><li>The official API reference for FoundationModels, including updates from iOS 18/macOS 15.</li><li><a href="https://machinelearning.apple.com/research/apple-foundation-models-tech-report-2025">Apple Foundation Models Tech Report (2025)</a></li><li>A deep dive into how Apple trains, evaluates, and deploys its on-device language models.</li><li><a href="https://developer.apple.com/videos/play/wwdc2025/286">WWDC 2025: Meet Foundation Models</a></li><li>Apple’s official session introducing FoundationModels, with live demos and best practices.</li></ul><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad663e60d716" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside FoundationModels: How Sessions Actually Work]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/inside-foundationmodels-how-sessions-actually-work-1a250bb30110?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a250bb30110</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 15:42:20 GMT</pubDate>
            <atom:updated>2025-08-18T14:58:10.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*00keuaRBUWuQnxZCj1yT0Q@2x.png" /></figure><h4><strong>From Prompt to Prediction: The Life of a Session in FoundationModels</strong></h4><p>In the <a href="https://medium.com/@luizfernandosalvaterra/a7deac7719fc">first article of this series</a>, we explored the basics of Apple’s new <strong>FoundationModels</strong> framework — including how to run your first prompt on-device using Swift, and what makes this privacy-first approach to AI so powerful.</p><p>Now it’s time to go deeper.</p><p>At the core of every interaction with <strong>FoundationModels</strong> is a <strong>Session</strong> — a lightweight, stateful container that manages your instructions, prompts, and responses. While the high-level API may seem simple, what’s happening under the hood is more complex and critical to building real-world applications.</p><p>In this article, we’ll take a deep dive into LanguageModelSession:</p><ul><li>How it maintains context across multiple prompts</li><li>The difference between <strong>instructions</strong> and <strong>prompts</strong></li><li>How to avoid hitting the 4,096-token context window limit</li><li>And how to control the model’s behavior and output at a granular level</li></ul><p>If you want to move beyond simple one-off generations and start building <strong>intelligent, multi-turn interactions</strong>, understanding sessions is the key.</p><h3>Sessions, Prompts, Instructions, and Responses — How It All Works</h3><p>To interact with <strong>FoundationModels</strong>, everything revolves around a LanguageModelSession. Whether you’re building a chatbot, an AI assistant, or simply generating dynamic content, understanding how sessions manage prompts, instructions, and responses is essential.</p><p>Here’s how it works in practice, step by step:</p><h4>1. Creating a Session</h4><p>You start by creating a LanguageModelSession. This object manages the conversational context and configuration.</p><pre>let session = LanguageModelSession()</pre><p>There are two ways to use sessions:</p><ul><li><strong>Single-turn interaction</strong>: Create a new session for each prompt if you don’t want the model to retain prior context. This approach is useful for isolated tasks like summarization, translation, classification, or auto-complete — where each request is independent and doesn’t benefit from prior interactions.</li><li><strong>Multi-turn interaction</strong>: Reuse the same session across multiple prompts to maintain continuity. The session stores all prompts, instructions, and outputs in its context window. Ideal for use cases like conversational agents, guided flows, educational tutors, or assistants that need to remember the ongoing dialogue and build upon previous steps.</li></ul><h4>2. Understanding Prompts</h4><p>A <strong>prompt</strong> is the input message or question you give to the model — it’s what you want the model to respond to.</p><p>Examples:</p><pre>let shortPrompt = &quot;What&#39;s a good month to visit Rio de Janeiro?&quot;<br>let specificPrompt = &quot;Write a profile for the dog breed Siberian Husky using three sentences.&quot;</pre><p>Prompt writing tips:</p><ul><li><strong>Be clear and focused</strong>: Stick to one task per prompt.</li><li><strong>Keep it concise</strong>: Long, multi-part prompts can slow down generation and lead to inconsistent output.</li><li><strong>Guide the length</strong>: Add phrases like <em>“in three sentences”</em> or <em>“in a single paragraph”</em> to speed up responses and limit verbosity.</li><li><strong>Use natural, conversational tone</strong>: The model responds best to prompts that feel like real language.</li></ul><h4><strong>3. Using Instructions</strong></h4><p><strong>Instructions</strong> shape the behavior of the model across the entire session — they act like system-level directives and <strong>are prioritized above the individual prompts</strong>.</p><p>You can set them when creating the session:</p><pre>let instructions = &quot;&quot;&quot;<br>You are a helpful assistant.<br>Always respond in a friendly, concise tone.<br>&quot;&quot;&quot;<br>let session = LanguageModelSession(instructions: instructions)w</pre><p>Good instruction practices:</p><ul><li>Define the <strong>role</strong>: e.g. “You are a travel planner.”</li><li>Specify <strong>actions</strong>: e.g. “Suggest three weekend getaway ideas.”</li><li>Set <strong>style preferences</strong>: e.g. “Keep the response under 50 words.”</li><li>Establish <strong>safety limits</strong>: e.g. “Politely refuse to give medical advice.”</li></ul><blockquote><em>Pro tip: You can even include </em><strong><em>example responses</em></strong><em> in your instructions to help the model learn the expected tone or structure.</em></blockquote><h4>4. Generating Responses</h4><p>To get a response, call respond(to:) on your session asynchronously:</p><pre>let prompt = &quot;Making homemade bread&quot;<br>let response = try await session.respond(to: prompt)<br>print(response.content)</pre><p>Keep in mind:</p><ul><li>A session can only process <strong>one request at a time</strong>. Calling respond(to:) again before the previous call finishes will throw a runtime error.</li><li>You can check session.isResponding to know whether the model is still working.</li></ul><p>By combining instructions and prompts in a single LanguageModelSession, you gain fine-grained control over how the model behaves — from tone and style to memory and output length.</p><h4>Instructions vs No Instructions — A Side-by-Side Example</h4><p>To better understand how instructions influence the model’s behavior, let’s compare two responses generated with the <strong>exact same prompt</strong>:</p><pre>import SwiftUI<br>import Playgrounds<br>import FoundationModels<br><br><br>#Playground {<br>    let prompt = &quot;List three cities to visit in Brazil.&quot;<br>    let instructions = &quot;&quot;&quot;<br>    You are a sophisticated travel writer. Respond with vivid, elegant descriptions in a formal tone.<br>    &quot;&quot;&quot;<br><br>    let noInstructionsSession = LanguageModelSession()<br>    let noInstructionsResponse = try await noInstructionsSession.respond(to: prompt)<br>    print(noInstructionsResponse.content)<br><br>   <br>    let instructionsSession = LanguageModelSession(instructions: instructions)<br>    let instructionsResponse = try await instructionsSession.respond(to: prompt)<br>    print(instructionsResponse.content)<br>}</pre><p><strong>Without Instructions</strong></p><p>When no instructions are provided, the model defaults to a neutral, informative tone:</p><pre>Here are three cities in Brazil that are popular for their unique attractions and cultural experiences:<br><br>1. **Rio de Janeiro**<br><br>2. **São Paulo**<br><br>3. **Salvador**</pre><p><strong>With Instructions</strong></p><p>With instructions like <strong>“You are a sophisticated travel writer. Respond with vivid, elegant descriptions in a formal tone.” </strong>The model’s response transforms dramatically:</p><pre>Certainly! Brazil, with its rich tapestry of culture, history, and natural beauty, offers a plethora of destinations that are sure to captivate the traveler. Here are three cities that stand out as must-visit:<br><br>1. **Rio de Janeiro**: Known as the &quot;City of Eternal Spring,&quot; Rio de Janeiro is a vibrant metropolis that enchants visitors with its stunning landscapes and lively spirit. The iconic Christ the Redeemer statue overlooks the city from atop the Corcovado Mountain, offering breathtaking panoramic views. The lively streets of Copacabana and Ipanema are renowned for their sun-drenched beaches and samba rhythms that fill the air. A visit to the lush Tijuca Forest provides a serene escape, while the colorful streets of Santa Teresa invite exploration with their bohemian charm and artistic flair.<br><br>2. **São Paulo**: As the largest city in Brazil, São Paulo is a bustling hub of commerce, culture, and innovation. Its skyline is dominated by the impressive Neo-Gothic architecture of the São Paulo Cathedral, a testament to the city&#39;s rich historical tapestry. The vibrant neighborhoods of Vila Madalena and Vila Mariana are celebrated for their eclectic art scenes and eclectic culinary delights. The city&#39;s cultural offerings are equally diverse, from the renowned Museum of Art to the electrifying electronic music scene that pulses through its many clubs and festivals.<br><br>3. **Salvador**: Nestled along the Atlantic coast, Salvador is a city that beautifully fuses African, European, and indigenous influences into a vibrant mosaic of culture and history. The historic Pelourinho district, with its cobblestone streets and colonial architecture, offers a glimpse into the city&#39;s storied past. Music and dance, particularly the infectious rhythms of samba and the mesmerizing frevo, are an integral part of Salvador&#39;s soul. The nearby beaches of Porto da Barra and Itapuã provide a perfect backdrop for sun-soaked relaxation and seaside strolls.<br><br>Each of these cities offers a unique glimpse into the diverse and dynamic character of Brazil, inviting travelers to immerse themselves in its vibrant tapestry of life.The same information is presented, but now it’s wrapped in tone, context, and intent, aligned with your app’s voice.</pre><p>Instructions give you a powerful way to steer the model’s output — making it more conversational, technical, friendly, humorous, or even safe, depending on your app’s goals. They’re especially valuable when you want <strong>consistent voice and behavior</strong> across multiple prompts. <br>Now let&#39;s explore how this context builds up over time, what the 4,096-token limit means in practice, and how to avoid the infamous exceededContextWindowSize error.</p><h3>How Context Accumulation Works</h3><p>When using LanguageModelSession, it’s important to understand that the model maintains a <strong>running context</strong> of everything that happens during that session — including:</p><ul><li>The <strong>initial instructions</strong></li><li>Every <strong>prompt</strong> you send</li><li>Every <strong>response</strong> the model generates</li></ul><p>This running context is critical for multi-turn interactions, as it helps the model “remember” prior exchanges. However, it also introduces a limitation: the <strong>context window</strong>.</p><h4>The 4,096-token Limit</h4><p>Apple’s current on-device model (<strong>foundation-small</strong>) supports a <strong>maximum of 4,096 tokens</strong> per session. That means the <strong>combined total of </strong>instructions, all prompts and all responses must remain within this token budget.</p><p>Rough estimate:</p><ul><li>1 token ≈ 3–4 characters for English, Spanish, etc</li><li>1 token ≈ 1 character in Chinese, Japanese, or Korean</li></ul><p>Every session maintains a complete record of the interaction — including the instructions, each prompt, and every response — through the session.transcript property. Think of it as a running <strong>script</strong> or <strong>conversation log</strong>, where each turn is stored chronologically. This is especially useful for debugging, visualizing the full context sent to the model, or displaying the interaction in a chat-style UI. Since the entire context is what the model “sees” on every new generation, inspecting the transcript gives you full visibility into the reasoning and behavior of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*G4RGnEX8iP8056EzvXAThA.png" /></figure><blockquote><em>Because the transcript grows with each interaction — including all prompts, responses, and instructions — it’s surprisingly easy to exceed the 4,096-token limit due to the cumulative nature of the context window.</em></blockquote><p><strong>What happens when you exceed the limit?</strong></p><p>If the session accumulates more than 4,096 tokens, <strong>FoundationModels</strong> will throw this error:</p><pre>LanguageModelSession.GenerationError.exceededContextWindowSize</pre><p>When that happens, your session has <strong>grown too large</strong> for the model to handle — and no further prompts will work until you start a <strong>new session. </strong>Here are two effective strategies to recover gracefully:</p><h4>1. Condense the Transcript</h4><p>One simple and effective approach is to create a <strong>new session</strong> that retains just the essential parts of the conversation: the initial instruction and the most recent prompt or exchange.</p><pre>func newSession(previousSession: LanguageModelSession) -&gt; LanguageModelSession {<br>    let allEntries = previousSession.transcript.enumerated().map { $1 }<br><br>    var condensedEntries: [Transcript.Entry] = []<br>    if let firstEntry = allEntries.first {<br>        condensedEntries.append(firstEntry) // usually the instruction<br>        if allEntries.count &gt; 1, let lastEntry = allEntries.last {<br>            condensedEntries.append(lastEntry) // latest prompt or response<br>        }<br>    }<br><br>    let condensedTranscript = Transcript(entries: condensedEntries)<br>    return LanguageModelSession(transcript: condensedTranscript)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDKJ5Czi-0Oxt3HlP1-vtA.png" /></figure><p>This allows you to preserve continuity without starting completely from scratch — ideal for keeping the user’s intent alive in long interactions.</p><h4>2. Summarize the Session</h4><p>Another technique is to <strong>summarize the session so far</strong> and start a new session with that summary as the context.</p><p>You can do this manually or by asking the model itself to summarize:</p><pre>let summaryPrompt = &quot;Summarize this conversation briefly for context:&quot;<br>let summaryInput = session.transcript.description // or a custom formatter<br>let summary = try await summarizerSession.respond(to: summaryPrompt + summaryInput)<br><br>let condensedSession = LanguageModelSession(instructions: &quot;You are continuing a conversation. Here&#39;s what happened before:\n\(summary.content)&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8T8O-EvzWKbAGTYwpZOGKw.png" /></figure><p>This is especially helpful for long-form assistants, chatbots, or workflows that involve extended sequences of questions.</p><p>By proactively managing the context — either through <strong>transcript pruning</strong> or <strong>semantic summarization</strong> — you can create scalable experiences that feel intelligent and coherent, even with the strict context limit of on-device models.</p><h3>Controlling Output Variability</h3><p>By default, language models are <strong>probabilistic</strong> — meaning they can return different outputs even when given the same prompt. This variability is often useful for creativity and exploration, but sometimes you need <strong>consistent</strong>, <strong>repeatable</strong>, or <strong>more controlled</strong> responses.</p><p><strong>FoundationModels</strong> gives you fine control over the model’s generation behavior using the GenerationOptions API.</p><h4>Deterministic Output with .greedy</h4><p>If you want the <strong>exact same output</strong> every time for a given prompt (useful for testing, caching, or UI consistency), set the sampling strategy to .greedy.</p><pre> func sameOutput(session: LanguageModelSession, prompt: String) async throws {<br>    let response = try await session.respond(<br>        to: prompt,<br>        options: GenerationOptions(sampling: .greedy)<br>    )<br>}</pre><blockquote><em>⚠️ This will only guarantee identical output </em><strong><em>within the same model version</em></strong><em>. If Apple updates the model, even </em><em>.greedy may produce slightly different results.</em></blockquote><h4>Controlling Randomness with temperature</h4><p>You can also adjust how “creative” or “random” the model is by tweaking the temperature. Lower temperatures make the model more predictable; higher values make it more expressive and surprising.</p><h4>Low Variance: More Focused and Stable</h4><pre>func lowVarianceOutput(session: LanguageModelSession, prompt: String) async throws {<br>    let response = try await session.respond(<br>        to: prompt,<br>        options: GenerationOptions(temperature: 0.5)<br>    )<br>}</pre><p>Use this when you want consistency across responses, with a bit of flexibility — great for structured answers like Q&amp;A, summaries, or internal tools.</p><h4>High Variance: More Creative and Surprising</h4><pre>func hiVarianceOutput(session: LanguageModelSession, prompt: String) async throws {<br>    let response = try await session.respond(<br>        to: prompt,<br>        options: GenerationOptions(temperature: 2.0)<br>    )<br>}</pre><p>Useful for brainstorming, storytelling, or when you’re looking for diverse ideas. Expect longer and more expressive outputs.</p><p>Choosing the right generation strategy depends on your use case. Here are some recommended settings:</p><ul><li><strong>Unit tests / repeatability: </strong>Use `.greedy` to ensure identical output for the same prompt (as long as the model version doesn’t change).</li><li><strong>UI hints / tooltips: </strong>Use temperature: 0.3–0.6 to produces low-variance outputs with slight randomness, ideal for UI elements.</li><li><strong>Summaries / consistency: </strong>Use temperature: ~0.5 to Balance and structure the responses — great for assistants, search helpers, and summaries.</li><li><strong>Story generation / ideation: </strong>Use temperature: 1.2–2.0 to Encourage creativity and expressive language for storytelling and brainstorming.</li></ul><h3>Conclusion</h3><p>Sessions are at the heart of how you interact with <strong>FoundationModels</strong>. They define not only the structure of your prompts and instructions, but also the boundaries of what the model can “remember” during a conversation. Understanding how transcripts grow, how to avoid context window overflow, and how to control output variability gives you the confidence to build smarter and more reliable AI features — all running privately on-device.</p><p>Now that you know how sessions really work, you’re ready to explore more advanced capabilities like <strong>Guided Generation</strong> — where model responses can be automatically mapped to Swift types, enabling powerful structured interactions.</p><p><em>Let’s keep pushing the boundaries of what’s possible with on-device intelligence.</em></p><h3>What’s Next</h3><p>In the next article, we’ll dive into one of the most powerful — and underrated — features of FoundationModels: <strong>Guided Generation</strong>.</p><p>You’ll learn how to:</p><ul><li>Steer the model to generate structured responses</li><li>Map outputs directly to your own Swift types and models</li><li>Control output format and structure with precision</li><li>Combine Guided Generation with Instructions for even smarter prompts</li></ul><p>Imagine generating a full UserProfile, SearchResult, or even QuizQuestion directly from natural language — all without post-processing.</p><p>If Sessions are the heart of <strong>FoundationModels</strong>, <strong>Guided</strong> <strong>Generation</strong> is the brain. And we’re just getting started.</p><p>Ready to level up your FoundationModels skills?<a href="https://medium.com/@luizfernandosalvaterra/guided-generation-with-foundationmodels-how-to-get-swift-structs-from-llms-ad663e60d716"> Read it now</a>.</p><p><strong>Missed the first article?</strong> Start from the beginning with <a href="https://medium.com/@luizfernandosalvaterra/exploring-apple-foundationmodels-privacy-first-ai-on-your-device-a7deac7719fc">Exploring Apple FoundationModels: Privacy-First AI on Your Device</a></p><h3>Official Resources</h3><p>Want to dive deeper into <strong>FoundationModels</strong> and Apple’s generative AI stack? Here are the most important links:</p><ul><li><a href="https://developer.apple.com/documentation/foundationmodels"><strong>FoundationModels Documentation</strong></a></li><li><a href="https://machinelearning.apple.com/research/introducing-apple-foundation-models"><strong>Apple Foundation Models Research Overview</strong></a></li><li><a href="https://developer.apple.com/videos/play/wwdc2025/286"><strong>WWDC 2025 Session: Meet Foundation Models</strong></a></li></ul><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a250bb30110" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Apple FoundationModels: Privacy-First AI on Your Device]]></title>
            <link>https://medium.com/@luizfernandosalvaterra/exploring-apple-foundationmodels-privacy-first-ai-on-your-device-a7deac7719fc?source=rss-f55f6d889eeb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7deac7719fc</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Luiz Fernando Salvaterra]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 01:19:53 GMT</pubDate>
            <atom:updated>2025-08-18T14:54:53.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*00keuaRBUWuQnxZCj1yT0Q@2x.png" /></figure><p><strong>How to Use Apple’s First LLM Model Today (Even in Beta)</strong></p><h3>Welcome to the New Era of On-Device AI</h3><p>At <strong>WWDC 2025</strong>, Apple unveiled a quiet revolution: the new <strong>FoundationModels</strong> framework. With it, Apple takes a bold step toward making powerful generative AI feel as native as UIKit or SwiftUI.</p><p>For the first time on Apple platforms, developers can now access a <strong>large language model (LLM)</strong> that runs <strong>directly on-device</strong> — enabling fast, private, and offline intelligence across iOS, macOS, iPadOS, and visionOS.</p><p>The first available model, foundation-small, comes with <strong>around 3 billion parameters</strong>, while this may sound modest compared to cloud giants like ChatGPT’s GPT-3.5 (which has <strong>175 billion parameters</strong>), Apple’s model is optimized for efficiency — running locally, privately, and in real time using the Neural Engine inside Apple Silicon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-9Yo0pJcioZxpjMN8jgfw.png" /></figure><p>The result? AI that’s fast, secure, and integrated — no cloud APIs required.</p><p>But There’s a Catch: i<strong>t’s Still in Beta! </strong>The <strong>FoundationModels</strong> framework is currently <strong>only available in beta</strong>, meaning you’ll need:</p><ul><li><strong>Xcode 16 beta</strong></li><li>A physical device running <strong>iOS 26, macOS 26, iPadOS 26, or visionOS 26.</strong></li><li>If you don’t own a compatible physical device, you can still try FoundationModels using the macOS 26 Beta and the Simulator — it works there too</li><li>And access to Apple’s <strong>on-device AI models</strong>, downloadable via <em>Settings &gt; General &gt; AI Models</em></li></ul><p>If you meet those requirements, you’re among the first developers with access to Apple’s native LLM capabilities — and this article will help you get started.</p><h4>What is FoundationModels?</h4><p><strong>FoundationModels</strong> is Apple’s new native framework for running generative AI models directly on-device. It provides a high-level, Swift-first API to interact with large language models (<strong>LLMs</strong>) and vision models, optimized for the Apple Neural Engine. The framework enables developers to perform tasks like text generation, summarization, classification, and embedding — all with minimal latency and no reliance on external servers.</p><p>Key capabilities include:</p><ul><li><strong>Content Generation</strong>: Produce context-aware, fluent responses using the default model.</li><li><strong>Summarization</strong>: Generate concise summaries from long text inputs.</li><li><strong>Guided Generation</strong>: Generate structured outputs by directly mapping the model’s response to predefined Swift types such as structs or enums. This ensures the output conforms to a known schema — ideal for safely generating code, commands, or structured data directly into your app’s models.</li><li><strong>Tool Calling</strong>: Allow the model to invoke predefined app functions, enabling AI-assisted workflows and task execution.</li><li><strong>On-Device Execution</strong>: No network calls — models are run entirely on Apple Silicon under the hood.</li></ul><p>With <strong>FoundationModels</strong>, Apple gives developers a unified, privacy-focused AI stack that seamlessly integrates with the platform, just like any other native framework.</p><h3>Limitations of the On-Device Model</h3><p>While the on-device Foundation Model (~3B parameters) delivers impressive performance for many language understanding tasks, it comes with <strong>important limitations</strong> that developers should keep in mind.</p><p>According to Apple’s own guidelines, this model is <a href="https://developer.apple.com/videos/play/wwdc2025/248"><strong>not recommended for code generation or advanced mathematical reasoning</strong></a>. Its compact size prioritizes efficiency and privacy, which means it lacks the scale needed to perform well on highly structured, logic-intensive tasks — such as writing Swift code, solving math problems, or handling complex tool orchestration. So what if you need more power?</p><p>Apple has also trained a <strong>larger, more capable model</strong> designed for server-side deployment via <strong>Private Cloud Compute</strong>. This model leverages a modern <a href="https://machinelearning.apple.com/research/apple-foundation-models-2025-updates"><strong>Parallel-Track Mixture-of-Experts (PT-MoE)</strong> </a>architecture and is already being used in Apple Intelligence to power more sophisticated generative tasks.</p><h3>Hands-on: Running FoundationModels in Xcode 26 Playgrounds</h3><p>To get started with FoundationModels, we’ll take advantage of a new feature in <strong>Xcode 26</strong>: the revamped <strong>Playgrounds</strong>. Unlike SwiftUI previews, which visualize views, Playgrounds let you write, execute and preview <strong>pure Swift code with async support</strong> — including code that interacts with FoundationModels — all in real time and inline.</p><p>This makes it the perfect environment to prototype and experiment with on-device AI without having to build a full app.</p><p>Let’s start with a simple example:</p><pre>import SwiftUI<br>import Playgrounds<br>import FoundationModels<br><br>#Playground {<br>    let session = LanguageModelSession()<br>    let response = try await session.respond(to: &quot;Give me a list of 5 cities in Brazil.&quot;)<br>    print(response.content)<br>}</pre><h4>What this code does:</h4><ul><li>LanguageModelSession() creates a new session for interacting with a foundation language model, using the default configuration (typically foundation-small).</li><li>respond(to:) sends a prompt string to the model and returns a generated response asynchronously.</li><li>The result is printed in the preview— in this case, a list of five Brazilian cities generated on-device by the model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNHAmHqZxtU6JS5_WXHdwA.png" /></figure><p>With just a few lines of code, you’ve now run a generative AI task <strong>entirely on-device</strong> using Apple’s <strong>FoundationModels</strong>. No networking, no cloud APIs — just pure Swift and local intelligence.</p><h4><strong>Checking for Model Availability</strong></h4><p>Before using <strong>FoundationModels</strong>, it’s crucial to verify whether the on-device language model is available. Not all devices or configurations support Apple’s generative features out of the box — and the model may not be ready immediately, even if the user has compatible hardware.</p><p>The recommended way to check availability is by accessing the .default instance of SystemLanguageModel. This uses the same system model leveraged by <strong>Apple Intelligence</strong>, and supports tasks like text generation.</p><p>Model availability depends on several runtime factors:</p><ul><li>The device must support <strong>Apple Intelligence</strong> (e.g. iPhone 15 Pro or newer, M-series Macs).</li><li>Apple Intelligence must be <strong>enabled by the user</strong> in Settings.</li><li>The model must be <strong>downloaded and ready</strong>, which may take time after the feature is first enabled.</li></ul><p>You should always check model availability at runtime, and design fallback UI for cases where the model is unavailable.</p><p>Here’s a SwiftUI example from the oficial documentation that demonstrates how to handle all cases gracefully:</p><pre>import SwiftUI<br>import FoundationModels<br><br>struct GenerativeView: View {<br>    private var model = SystemLanguageModel.default<br><br>    var body: some View {<br>        switch model.availability {<br>        case .available:<br>            // Display your AI-powered experience.<br>        case .unavailable(.deviceNotEligible):<br>            // Inform the user their device doesn&#39;t support Apple Intelligence.<br>        case .unavailable(.appleIntelligenceNotEnabled):<br>            // Prompt the user to enable Apple Intelligence in Settings.<br>        case .unavailable(.modelNotReady):<br>            // Let the user know the model is still downloading or initializing.<br>        case .unavailable(let unknownReason):<br>            // Handle other unexpected availability issues.<br>        }<br>    }<br>}</pre><h3>Heads Up: Context Window Limits Are Real</h3><p>While <strong>FoundationModels</strong> brings powerful on-device AI to your apps, it’s important to know that <strong>not everything is limitless</strong> — especially when it comes to how much text the model can handle in a single session.</p><p>Like most <strong>LLMs</strong>, Apple’s model has a <strong>context window</strong>: a limit on how many tokens it can process per session. The system model currently supports up to <strong>4,096 tokens</strong> — and that includes:</p><ul><li>Your system instructions</li><li>The user prompt(s)</li><li>The generated response(s)</li></ul><p>But… what’s a token? Think of a token as a chunk of text — usually:</p><ul><li><strong>1 token = 3–4 characters</strong> in languages like English, Spanish, or German</li><li><strong>1 token ≈ 1 character</strong> in more compact languages like Japanese, Chinese, or Korean</li></ul><p>So if you send a long prompt, multiple responses, and additional instructions all in the same session, you may eventually hit the <strong>context limit. </strong>When that happens, you’ll get the LanguageModelSession.GenerationError.exceededContextWindowSize error.</p><h4>How to deal with it:</h4><ul><li>Start a <strong>new session</strong> if you hit the limit.</li><li>Keep prompts <strong>short and focused</strong>.</li><li>If you need to process a lot of data, <strong>split it into smaller chunks</strong> and combine the results later.</li></ul><p>Don’t worry — we’ll dive deeper into best practices for managing context, memory, and streaming in a future article of this series.</p><h3>Conclusion</h3><p>With <strong>FoundationModels</strong>, Apple is opening the door to a new era of on-device intelligence — one that’s fast, private, and deeply integrated with the Apple ecosystem. While the framework is still in beta, it already provides powerful capabilities that allow developers to experiment with large language models in a way that feels native to Swift.</p><p>From generating content to classifying text or building AI-powered workflows, you’re no longer dependent on cloud APIs to deliver intelligent features. Instead, the power of generative AI is now literally in your users’ hands — running on their devices, on their terms.</p><p>And we’re just getting started.</p><h3>What’s Next</h3><p>Now that you’ve had your first look at <strong>FoundationModels</strong> and run your first on-device LLM prompt, it’s time to go deeper.</p><p>In the next article, we’ll explore one of the most important building blocks of the framework: <strong>sessions</strong>.</p><p>You’ll learn:</p><ul><li>The difference between <strong>instructions</strong> and <strong>prompts</strong>, and how each affects the model’s behavior</li><li>How to handle exceededContextWindowSize errors and avoid hitting the 4,096-token limit.</li><li>What actually happens under the hood when you create a LanguageModelSession</li><li>Techniques to <strong>control the model’s output</strong>, including adjusting temperature, maximum tokens, and system tone</li></ul><p><strong>Check out Part 2:</strong> <a href="https://medium.com/@luizfernandosalvaterra/inside-foundationmodels-how-sessions-actually-work-1a250bb30110">Inside FoundationModels — How Sessions Actually Work</a></p><p>Whether you want to build a chatbot, summarize long-form content, or safely generate structured responses, understanding sessions is the key to making <strong>FoundationModels</strong> truly work for you.</p><h3>Official Resources</h3><p>Want to dive deeper into FoundationModels and Apple’s generative AI stack? Here are the most important links:</p><ul><li><a href="https://developer.apple.com/documentation/foundationmodels"><strong>FoundationModels Documentation</strong></a></li><li><a href="https://machinelearning.apple.com/research/introducing-apple-foundation-models"><strong>Apple Foundation Models Research Overview</strong></a></li><li><a href="https://developer.apple.com/videos/play/wwdc2025/286"><strong>WWDC 2025 Session: Meet Foundation Models</strong></a></li></ul><h3>Enjoyed this article?</h3><p>If this guide helped you learn something new, consider supporting my work at <a href="https://buymeacoffee.com/luizfernandosalvaterra"><strong>Buy Me a Coffee</strong></a>. Your support keeps me writing more deep-dive articles like this for the iOS community.</p><p><em>I’ve been building iOS apps for more than 10 years and love sharing what I learn. If this article helped you, consider supporting me on </em><a href="https://buymeacoffee.com/luizfernandosalvaterra"><em>Buy Me a Coffee</em></a><em>.</em></p><p><a href="https://buymeacoffee.com/luizfernandosalvaterra">Luiz Fernando Salvaterra</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7deac7719fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>