<?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 Ahil NS on Medium]]></title>
        <description><![CDATA[Stories by Ahil NS on Medium]]></description>
        <link>https://medium.com/@eahilendran?source=rss-8d8df9c5eb5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XoOhfZSph6uOd7s3m0KEcg.jpeg</url>
            <title>Stories by Ahil NS on Medium</title>
            <link>https://medium.com/@eahilendran?source=rss-8d8df9c5eb5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:31:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eahilendran/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[Demystifying Swift Concurrency: Understanding async and async let]]></title>
            <link>https://medium.com/@eahilendran/demystifying-swift-concurrency-understanding-async-and-async-let-7f5982a12ef1?source=rss-8d8df9c5eb5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f5982a12ef1</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[async-vs-async-let]]></category>
            <category><![CDATA[async-let]]></category>
            <dc:creator><![CDATA[Ahil NS]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 02:51:52 GMT</pubDate>
            <atom:updated>2025-03-04T02:51:52.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift’s concurrency model is a game changer. With the introduction of async/await in Swift 5.5, writing asynchronous code has never been more natural. In this article, we focus on two essential aspects of this model: marking functions as asynchronous with async and launching concurrent tasks using async let. We’ll explore what each means, why you’d use one over the other, and how they work together to optimize performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ito6DkV2lS3dj8cRbBCWPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBIM55s5jy5LBfI5bAjs-g.png" /></figure><p><strong>What Does async Mean?</strong></p><p>When you mark a function with the async keyword, you’re indicating that it performs work asynchronously. Rather than blocking a thread until an operation completes, an async function can suspend its execution at an await call, letting other tasks run concurrently. This non-blocking behavior makes your code more responsive — especially in UI-driven apps.</p><p><strong>Key Points:</strong></p><p>• <strong>Non-blocking:</strong> Async functions suspend execution instead of blocking, allowing other operations to continue.</p><p>• <strong>Return Value:</strong> The return value is wrapped in a Swift task, so you always use await to retrieve it.</p><p>• <strong>Simpler Flow:</strong> The linear syntax makes asynchronous code look similar to synchronous code, easing readability and maintenance.</p><p><strong>What is async let?</strong></p><p>While async functions allow you to write non-blocking code, async let takes concurrency a step further. It lets you launch multiple asynchronous tasks simultaneously. Instead of waiting for one task to complete before starting the next, you kick off several tasks in parallel and then await their results together. This is especially useful when tasks are independent — for example, when loading multiple images or fetching data from different sources.</p><p><strong>Key Points:</strong></p><p>• <strong>Parallel Task Launch:</strong> Tasks declared with async let start executing concurrently.</p><p>• <strong>Efficient Awaiting:</strong> You await all the results at once, reducing total execution time to the duration of the slowest task.</p><p>• <strong>Ideal for Independent Work:</strong> Use async let when tasks don’t depend on one another.</p><p><strong>Code Example: Parallel vs. Sequential Image Loading</strong></p><p>Below is a complete SwiftUI project demonstrating both parallel and sequential execution. The code simulates fetching image URLs (with a delay) and measures the total time taken. A toggle in the UI allows switching between parallel execution using async let and sequential execution using plain await.</p><pre>import SwiftUI<br>// MARK: - View Model<br>@MainActor<br>@Observable<br>final class ImageLoaderViewModel {<br>    var imageURLs: [URL?] = []<br>    var loadingTime: TimeInterval = 0.0<br>    var isParallelExecution = true<br>    // Asynchronously fetch an image URL.<br>    // This simulates a network delay before returning a URL.<br>    private func fetchImageURL(for index: Int) async -&gt; URL? {<br>        let url = URL(string: &quot;https://picsum.photos/200/300?random=\(index)&quot;)<br>        do {<br>            try await Task.sleep(nanoseconds: 500_000_000)<br>            debugPrint(&quot;✅ Fetched image URL \(index)&quot;)<br>            return url<br>        } catch {<br>            debugPrint(&quot;❌ Failed to fetch image URL \(index): \(error)&quot;)<br>            return nil<br>        }<br>    }<br>    <br>    // Public method to load images based on the execution mode.<br>    // It records the start time, calls the appropriate loading method,<br>    // and then calculates the total loading time.<br>    func loadImages() {<br>        Task {<br>            let startTime = Date()<br>            if isParallelExecution {<br>                await loadImagesInParallel()   // Launches tasks concurrently using async let<br>            } else {<br>                await loadImagesSequentially() // Executes tasks one after another with sequential await<br>            }<br>            loadingTime = Date().timeIntervalSince(startTime)<br>            debugPrint(&quot;⏱ Loading time: \(loadingTime) sec&quot;)<br>        }<br>    }<br>    <br>    // Load images concurrently using async let.<br>    // All image URL fetches start at the same time.<br>    private func loadImagesInParallel() async {<br>        async let firstURL = fetchImageURL(for: 1)<br>        async let secondURL = fetchImageURL(for: 2)<br>        async let thirdURL = fetchImageURL(for: 3)<br>        imageURLs = await [firstURL, secondURL, thirdURL]<br>    }<br>    <br>    // Load images sequentially.<br>    // Each fetch waits for the previous one to complete.<br>    private func loadImagesSequentially() async {<br>        let firstURL = await fetchImageURL(for: 1)<br>        let secondURL = await fetchImageURL(for: 2)<br>        let thirdURL = await fetchImageURL(for: 3)<br>        imageURLs = [firstURL, secondURL, thirdURL]<br>    }<br>}<br>// MARK: - Content View<br>struct ContentView: View {<br>    @State private var viewModel = ImageLoaderViewModel()<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;SwiftUI Async Let Demo: Parallel vs Sequential Image Loading&quot;)<br>                .font(.title)<br>                .multilineTextAlignment(.center)<br>            <br>            HStack {<br>                ForEach(viewModel.imageURLs.indices, id: \.self) { index in<br>                    if let url = viewModel.imageURLs[index] {<br>                        AsyncImage(url: url) { image in<br>                            image<br>                                .resizable()<br>                                .scaledToFit()<br>                                .frame(width: 100, height: 150)<br>                        } placeholder: {<br>                            ProgressView()<br>                        }<br>                    } else {<br>                        ProgressView()<br>                            .frame(width: 100, height: 150)<br>                    }<br>                }<br>            }<br>            <br>            if viewModel.loadingTime &gt; 0 {<br>                Text(&quot;Time Taken: \(viewModel.loadingTime) sec&quot;)<br>                    .font(.subheadline)<br>            }<br>            <br>            // Toggle to switch between parallel (async let) and sequential (await) execution.<br>            Toggle(&quot;Load in Parallel&quot;, isOn: $viewModel.isParallelExecution)<br>            <br>            Button(&quot;Reload Images&quot;) {<br>                viewModel.loadImages()<br>            }<br>            .buttonStyle(.borderedProminent)<br>        }<br>        .padding()<br>        .task {<br>            viewModel.loadImages() // Automatically load images when the view appears.<br>        }<br>    }<br>}<br>// MARK: - Preview<br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><p><strong>How It Works</strong></p><p><strong>Async Functions with await</strong></p><p>• <strong>fetchImageURL(for:):</strong></p><p>This function is marked as async and simulates a network request by sleeping for 0.5 seconds. When called, it suspends execution until the delay is over, then returns a URL.</p><p>• <strong>Sequential vs. Parallel Execution:</strong></p><p>• In <strong>sequential mode</strong>, each call to fetchImageURL(for:) is awaited one after the other. The total time is the sum of the delays.</p><p>• In <strong>parallel mode</strong>, using async let, all three fetch tasks start at the same time. The code awaits all of them together, so the total time is roughly equal to the slowest individual task.</p><p><strong>Using async let</strong></p><p>The loadImagesInParallel() function demonstrates how to start multiple asynchronous tasks concurrently with async let. This is particularly effective when the tasks do not depend on each other and can run simultaneously to reduce wait time.</p><p><strong>Conclusion</strong></p><p>Swift’s concurrency model — with its async functions and async let — provides a powerful and elegant way to write asynchronous code. Marking functions as async allows your code to suspend and resume efficiently, while async let gives you the ability to run multiple tasks concurrently. This demo illustrates the performance benefits when tasks are independent, and how a simple toggle can let you switch between sequential and parallel execution.</p><p>Happy coding, and leverage Swift’s concurrency features to build responsive, high-performance apps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f5982a12ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Senior iOS Developer Interview Questions 2025: Swift Focus (Part 2)]]></title>
            <link>https://medium.com/@eahilendran/top-senior-ios-developer-interview-questions-2025-swift-focus-part-2-c262ab2e9676?source=rss-8d8df9c5eb5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c262ab2e9676</guid>
            <dc:creator><![CDATA[Ahil NS]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 03:41:42 GMT</pubDate>
            <atom:updated>2025-02-18T03:45:31.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSrN4_syTx2FyH9J7mwFpw.png" /></figure><p>If you’re preparing for an <strong>iOS interview</strong>, understanding Swift’s core concepts is crucial. In this article, we’ll break down some of the <strong>most commonly asked iOS interview questions</strong>, with <strong>clear explanations, examples, and comparison tables</strong> to make learning easier.</p><p>Check out <strong>SwiftUI Interview Questions Part 1</strong> at: <a href="https://medium.com/@eahilendran/ios-developer-interview-question-2025-part-1-swift-20d2517f1e32">iOS Developer Interview Questions 2025 — Part 1 (SwiftUI)</a>.</p><h3>What Are Higher-Order Functions?</h3><p>In Swift, a <strong>higher-order function</strong> is a function that:</p><p>✅ Takes another function as an argument <strong>(function as a parameter)</strong>.<br>✅ Returns a function as its result <strong>(function as a return value)</strong>.<br>✅ Or both!</p><p>Higher-order functions make Swift <strong>more expressive, concise, and functional</strong>.</p><p><strong>🔹 Why Use Higher-Order Functions?</strong></p><p>✅ <strong>Reduces boilerplate code</strong> — Eliminates for loops.<br>✅ <strong>Improves code readability</strong> — Makes code <strong>declarative</strong> rather than <strong>imperative</strong>.<br>✅ <strong>Encourages functional programming</strong> — Makes operations <strong>composable</strong>.</p><p><strong>Common Higher-Order Functions in Swift</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxh0nxgXZSHWfk0cIrgq2w.png" /></figure><p><strong>🔹 1. map(_:) — Transform Elements</strong></p><p>map(_:) applies a function to <strong>each element in a collection</strong> and returns a new collection.</p><p><strong>Example: Squaring Numbers</strong></p><pre>let numbers = [1, 2, 3, 4, 5]<br>let squaredNumbers = numbers.map { $0 * $0 }<br><br>print(squaredNumbers) // Output: [1, 4, 9, 16, 25]</pre><p><strong>🔹 2. filter(_:) — Selecting Elements</strong></p><p>filter(_:) returns a <strong>new collection</strong> containing only elements that match a condition.</p><pre>let numbers = [1, 2, 3, 4, 5, 6]<br>let evenNumbers = numbers.filter { $0 % 2 == 0 }<br><br>print(evenNumbers) // Output: [2, 4, 6]</pre><p><strong>🔹 3. reduce(_:_:) — Combine Elements</strong></p><p>reduce(_:_:) <strong>combines all elements into a single value</strong>.</p><p><strong>Example: Summing an Array</strong></p><pre>let numbers = [1, 2, 3, 4, 5]<br>let sum = numbers.reduce(0) { $0 + $1 }<br>let sumV2 = numbers.reduce(0, +)<br><br>print(sum) // Output: 15<br>print(sumV2) // Output: 15</pre><p><strong>🔹 4. compactMap(_:) — Remove nil Values</strong></p><p>compactMap(_:) transforms elements and removes <strong>nil</strong> values.</p><pre>let strings = [&quot;1&quot;, &quot;two&quot;, &quot;3&quot;, &quot;four&quot;, &quot;5&quot;]<br>let numbers = strings.compactMap { Int($0) }<br><br>print(numbers) // Output: [1, 3, 5]</pre><ul><li>It <strong>automatically removes nil values</strong> while transforming elements</li></ul><p><strong>🔹 5. flatMap(_:) — Flatten Nested Collections</strong></p><p>flatMap(_:) transforms each element and <strong>flattens</strong> the result into a single array.</p><p><strong>Example: Flattening an Array of Arrays</strong></p><pre>let nestedArray = [[1, 2], [3, 4], [5, 6]]<br>let flatArray = nestedArray.flatMap { $0 }<br><br>print(flatArray) // Output: [1, 2, 3, 4, 5, 6]</pre><ul><li><strong>Eliminates nested loops</strong> when working with arrays of arrays.</li></ul><p><strong>🔹 6. sorted(_:) — Sorting Collections</strong></p><p>sorted(_:) arranges elements based on a condition.</p><p><strong>Example: Sorting in Descending Order</strong></p><pre>let numbers = [5, 1, 4, 2, 3]<br>let sortedNumbers = numbers.sorted { $0 &gt; $1 }<br><br>print(sortedNumbers) // Output: [5, 4, 3, 2, 1]</pre><p><strong>🚀 Final Thoughts</strong></p><p>Higher-order functions <strong>simplify code</strong> and make Swift more <strong>expressive and functional</strong>. 🎯</p><p>✅ <strong>Use map, filter, and reduce</strong> to write <strong>concise</strong>, <strong>declarative</strong>, and <strong>efficient</strong> code.<br>✅ <strong>Practice using them instead of loops</strong> to improve code readability.</p><h3>What is a Closure in Swift?</h3><p>A <strong>closure</strong> in Swift is a <strong>self-contained block of code</strong> that can be passed around and executed at a later time. Closures are similar to <strong>functions</strong>, but they:</p><p>✅ Can be <strong>stored in variables or constants</strong>.<br>✅ Can <strong>capture and store references</strong> to variables from their surrounding context.<br>✅ Can be <strong>used as function parameters and return values</strong>.</p><p>Closures are widely used in <strong>completion handlers</strong>, <strong>higher-order functions</strong>, and <strong>asynchronous programming</strong>.</p><p><strong>Closure Syntax in Swift</strong></p><p>1️⃣ <strong>Parameters</strong> (like function parameters).<br>2️⃣ <strong>Return Type</strong> (optional).<br>3️⃣ <strong>Body</strong> (actual implementation).</p><p><strong>Basic Closure Syntax</strong></p><pre>{ (parameters) -&gt; ReturnType in<br>    // Closure body (code to execute)<br>}</pre><p><strong>🔹 Examples of Closures</strong></p><p><strong>✅ 1. Assigning a Closure to a Variable</strong></p><pre>let greet = { (name: String) -&gt; String in<br>    return &quot;Hello, \(name)!&quot;<br>}<br><br>print(greet(&quot;Alice&quot;)) // Output: Hello, Alice!</pre><p><strong>✅ 2. Closures as Function Parameters (Higher-Order Functions)</strong></p><p>Closures are often used as <strong>arguments</strong> in functions.</p><pre>func performAction(action: () -&gt; Void) {<br>    print(&quot;Starting action...&quot;)<br>    action()<br>    print(&quot;Action completed.&quot;)<br>}<br><br>performAction {<br>    print(&quot;Running custom action!&quot;) <br>}<br><br><br>Output:<br>Starting action...<br>Running custom action!<br>Action completed.</pre><p><strong>✅ 3. Trailing Closure Syntax (Simplifying Code)</strong></p><p>When a closure is the <strong>last argument</strong> of a function, we can use <strong>trailing closure syntax</strong>.</p><p>🔹 <strong>Explanation</strong>:</p><pre>let numbers = [1, 2, 3, 4, 5]<br>let squaredNumbers = numbers.map { $0 * $0 }<br>print(squaredNumbers) // Output: [1, 4, 9, 16, 25]</pre><ul><li>map { $0 * $0 } is a <strong>trailing closure</strong> that squares each element in numbers.</li><li>$0 is <strong>Swift’s shorthand syntax</strong> for referring to the first parameter.</li></ul><p><strong>✅ 4. Capturing Values in Closures</strong></p><p>Closures can <strong>capture and store references</strong> to variables from their surrounding scope.</p><pre>func makeCounter() -&gt; () -&gt; Int {<br>    var count = 0<br>    return {<br>        count += 1<br>        return count<br>    }<br>}<br><br>let counter = makeCounter()<br>print(counter()) // Output: 1<br>print(counter()) // Output: 2<br>print(counter()) // Output: 3</pre><p>🔹 <strong>Explanation</strong>:</p><ul><li>The closure <strong>captures count</strong> and maintains its state <strong>even after makeCounter() exits</strong>.</li><li>Each time counter() is called, <strong>count is updated</strong>.</li></ul><p><strong>5. Escaping vs. Non-Escaping Closures</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9825IuWN59rSVfPQ1DXEw.png" /></figure><p><strong>Use Cases of Closures</strong></p><p>✅ <strong>Completion Handlers</strong> (e.g., network requests)<br>✅ <strong>Asynchronous Operations</strong> (e.g., animations, downloading data)<br>✅ <strong>Functional Programming</strong> (e.g., map, filter, reduce)<br>✅ <strong>Custom Sorting &amp; Callbacks</strong></p><h3>Array vs. Set — What’s the Difference?</h3><p>In Swift, both <strong>Array</strong> and <strong>Set</strong> are collection types used to store multiple values. However, they have <strong>different characteristics</strong> and are optimized for <strong>different use cases</strong>.</p><p><strong>Key Differences Between Array and Set</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1_koe_rGO7cVK485Dpjgg.png" /></figure><p><strong>Example Usage of Array and Set in Swift</strong></p><p><strong>1️⃣ Using an Array</strong></p><pre>var numbersArray = [1, 2, 3, 4, 5, 5]<br>numbersArray.append(6)<br>print(numbersArray)  // Output: [1, 2, 3, 4, 5, 5, 6]</pre><p>✅ <strong>Allows duplicates<br></strong>✅ <strong>Maintains order</strong></p><p><strong>2️⃣ Using a Set</strong></p><pre>var numbersSet: Set&lt;Int&gt; = [1, 2, 3, 4, 5, 5]<br>numbersSet.insert(6)<br>print(numbersSet)  // Output: [6, 2, 3, 1, 5, 4] (Order is not guaranteed)</pre><p>❌ <strong>Does not allow duplicates<br></strong>❌ <strong>Order is not maintained<br></strong>✅ <strong>Fast lookups</strong> (contains(_:) is O(1))</p><p><strong>Set Operations in Swift</strong></p><pre>import UIKit<br>var backendDevs: Set = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]<br>var frontendDevs: Set = [&quot;E&quot;, &quot;F&quot;, &quot;C&quot;, &quot;D&quot;, &quot;G&quot;]<br>var fullstackDevs: Set = [&quot;C&quot;, &quot;D&quot;, &quot;H&quot;]<br>var juniorDevs: Set = [&quot;E&quot;, &quot;F&quot;, &quot;I&quot;, &quot;J&quot;]<br><br>// 🔹 Intersect - Common developers between backend and frontend teams<br>let sharedDevs = backendDevs.intersection(frontendDevs)<br>print(&quot;Developers working in both backend and frontend: \(sharedDevs)&quot;)<br><br>// 🔹 Subtract - Backend developers who are NOT fullstack developers<br>let backendOnlyDevs = backendDevs.subtracting(fullstackDevs)<br>print(&quot;Backend developers NOT in fullstack: \(backendOnlyDevs)&quot;)<br><br>// 🔹 Disjoint - Check if backend and junior devs share any members<br>let isSeparateTeams = backendDevs.isDisjoint(with: juniorDevs)<br>print(&quot;Are backend and junior developers completely different? \(isSeparateTeams)&quot;)<br><br>// 🔹 Union - All developers across backend and frontend teams<br>let allDevs = backendDevs.union(frontendDevs)<br>print(&quot;All developers in backend and frontend teams: \(allDevs)&quot;)<br><br>// 🔹 Exclusive - Developers who are in only one of backend or frontend teams<br>let uniqueSpecialists = backendDevs.symmetricDifference(frontendDevs)<br>print(&quot;Developers working exclusively in either backend or frontend: \(uniqueSpecialists)&quot;)<br><br>// 🔹 Subset - Check if all fullstack developers are also backend developers<br>let isFullstackSubset = fullstackDevs.isSubset(of: backendDevs)<br>print(&quot;Are all fullstack developers also backend developers? \(isFullstackSubset)&quot;)<br><br>// 🔹 Superset - Check if frontend team includes all junior developers<br>let isFrontendSuperset = frontendDevs.isSuperset(of: juniorDevs)<br>print(&quot;Does frontend team include all junior developers? \(isFrontendSuperset)&quot;)</pre><pre>🛠 Expected Output:</pre><pre>Developers working in both backend and frontend: [&quot;C&quot;, &quot;D&quot;]<br>Backend developers NOT in fullstack: [&quot;A&quot;, &quot;B&quot;]<br>Are backend and junior developers completely different? true<br>All developers in backend and frontend teams: [&quot;E&quot;, &quot;F&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;G&quot;]<br>Developers working exclusively in either backend or frontend: [&quot;E&quot;, &quot;F&quot;, &quot;A&quot;, &quot;B&quot;, &quot;G&quot;]<br>Are all fullstack developers also backend developers? false<br>Does frontend team include all junior developers? false</pre><p><strong>When to Use Array vs. Set?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUTo6OxqK6odijlHqBr08g.png" /></figure><p><strong>🔥 Performance Comparison</strong></p><p><strong>Time Complexities</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gadqRGCcNT05d15x8kzVA.png" /></figure><p><strong>🎯 Final Thoughts</strong></p><p>✅ Use Array when order matters or duplicates are needed.<br>✅ Use Set when uniqueness is required or fast lookups are needed.</p><h3><strong>What is an Optional in Swift?</strong></h3><p>One of the goals of <strong>Swift</strong> is to be a <strong>safe</strong> programming language. Unlike other languages, <strong>variables cannot be nil by default</strong>.</p><p>To make a variable nullable, we <strong>explicitly</strong> opt into this behavior using Optional&lt;T&gt;.</p><p><strong>🔹 Declaring an Optional</strong></p><pre>var name: String? = &quot;John&quot;</pre><p>Adding ? after the type makes it <strong>optional</strong>, meaning it can either contain a value <strong>or be nil</strong>.</p><p><strong>🔹 Handling Optionals</strong></p><p>There are two ways to <strong>handle</strong> an optional value:</p><p>✅ <strong>Safe Ways</strong>:</p><ul><li><strong>Optional Chaining (?.)</strong></li><li><strong>Conditional Binding (if let / guard let)</strong></li><li><strong>Nil Coalescing (??)</strong></li></ul><p>❌ <strong>Unsafe Way</strong>:</p><ul><li><strong>Force Unwrapping (!)</strong> — should be <strong>avoided</strong> unless you’re certain the value isn’t nil.</li></ul><p><strong>🔹 Example Code</strong></p><pre>var name: String? = &quot;John&quot;<br>// Safe unwrapping<br>print(name ?? &quot;No name&quot;)<br>if let unwrappedName = name {<br>    print(unwrappedName) // &quot;John&quot;<br>}<br>// Unsafe force unwrapping<br>let forceUnwrap = name! // ❌ Crashes if `name` is nil</pre><p><strong>🔹 Comparison Table</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLJYhmvzVsq0_gwNRAkF7A.png" /></figure><p><strong>🔹 Recap</strong></p><p>Optionals help ensure <strong>type safety</strong> in Swift. Always prefer <strong>safe unwrapping techniques</strong> to prevent runtime crashes. 🚀</p><h3><strong>What is the Difference Between @escaping and Non-@escaping Closures?</strong></h3><p>Closures are <strong>self-contained blocks of functionality</strong> that can be passed around and used later. In Swift, closures are <strong>non-escaping by default</strong>, but we can mark them as @escaping when needed.</p><p><strong>🔹 What is a Non-Escaping Closure?</strong></p><p>A <strong>non-escaping closure</strong> is a closure that <strong>does not outlive the function</strong> it was passed into. Swift automatically assumes that closures are <strong>non-escaping</strong> unless explicitly marked with @escaping.</p><p><strong>✅ Characteristics of Non-Escaping Closures:</strong></p><ul><li>Executed <strong>before</strong> the function returns.</li><li>No need for memory management concerns.</li><li>The compiler can <strong>optimize performance</strong>.</li></ul><p><strong>🔹 Example of a Non-Escaping Closure:</strong></p><pre>func performTask(action: () -&gt; Void) {<br>    action()  // Executed immediately within this function<br>}</pre><pre>performTask {<br>    print(&quot;Task completed!&quot;)<br>}</pre><p>✅ <strong>Since action executes before performTask returns, it is a non-escaping closure.</strong></p><p><strong>🔹 What is an Escaping Closure?<br></strong>An <strong>escaping closure</strong> is a closure that <strong>outlives the function</strong> it was passed into, meaning it can be executed <strong>later</strong>. In Swift, we must explicitly mark these closures using @escaping.</p><p><strong>✅ Characteristics of Escaping Closures:</strong></p><ul><li>Stored <strong>beyond</strong> the function’s scope.</li><li>Typically used in <strong>asynchronous operations</strong> (e.g., network calls).</li><li>Needs careful handling to <strong>avoid memory leaks</strong>.</li></ul><p><strong>🔹 Example of an Escaping Closure:</strong></p><pre>class NetworkManager {<br>    var completionHandler: (() -&gt; Void)?</pre><pre>func fetchData(completion: @escaping () -&gt; Void) {<br>        completionHandler = completion  // Stored for later use<br>        DispatchQueue.global().async {<br>            sleep(2) // Simulating a network request<br>            DispatchQueue.main.async {<br>                completion()<br>            }<br>        }<br>    }<br>}</pre><pre>let manager = NetworkManager()<br>manager.fetchData {<br>    print(&quot;Data fetched!&quot;)<br>}</pre><p>✅ <strong>Since the completion closure is stored and executed after fetchData() returns, it must be marked as @escaping.</strong></p><p><strong>🔹 Key Differences Between Non-Escaping and Escaping Closures</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtV9yjKgKxNbBnj0HiK-RA.png" /></figure><p><strong>🔹 Handling Memory Leaks in Escaping Closures</strong></p><p>Since <strong>escaping closures</strong> can be stored for later execution, they may lead to <strong>retain cycles</strong> if a class holds a strong reference to self. To <strong>prevent memory leaks</strong>, use <strong>weak references ([weak self])</strong>.</p><p><strong>🔹 Example: Preventing Retain Cycles</strong></p><pre>class DataFetcher {<br>    func loadData(completion: @escaping () -&gt; Void) {<br>        DispatchQueue.global().async { [weak self] in<br>            sleep(2)  // Simulating delay<br>            DispatchQueue.main.async {<br>                completion()<br>            }<br>        }<br>    }<br>}</pre><p>✅ <strong>Using [weak self] ensures that self is not strongly retained, preventing memory leaks.</strong></p><p>💡 <strong>Tip:</strong> <strong>Prefer non-escaping closures whenever possible</strong> for better performance and safer memory management.</p><p><strong>🚀 Conclusion</strong></p><ul><li><strong>Non-escaping closures</strong> execute within the function and are optimized for performance.</li><li><strong>Escaping closures</strong> persist beyond the function’s scope and require careful memory management.</li><li>Always <strong>use [weak self]</strong> in escaping closures to prevent <strong>retain cycles</strong>.</li></ul><h3><strong>Computed Property vs. Method: When to Use Which?</strong></h3><p>In Swift, we often need to encapsulate logic that <strong>returns a value</strong>. We have two options:<br>1. <strong>Computed Properties<br></strong>2. <strong>Methods (Functions)</strong></p><p><strong>🔹 What is a Computed Property?<br></strong>A <strong>computed property</strong> is a property that doesn’t store a value but <strong>computes it dynamically</strong> whenever accessed.</p><p><strong>✅ Characteristics of Computed Properties:</strong></p><ul><li><strong>No stored value</strong> — it calculates a result each time it’s accessed.</li><li><strong>Idempotent</strong> — should return the same result when called multiple times with the same state.</li><li><strong>No Side Effects</strong> — should not modify any external state.</li></ul><p><strong>🔹 Example: Computed Property</strong></p><pre>struct Circle {<br>    var radius: Double<br>    var area: Double {  // Computed Property<br>        return Double.pi * radius * radius<br>    }<br>}<br><br><br>let circle = Circle(radius: 5)<br>print(circle.area) // Output: 78.54</pre><p>✅ <strong>Why is area a computed property?</strong></p><ul><li>It does <strong>not</strong> modify any state.</li><li>It returns the <strong>same result</strong> for the same radius.</li><li>It runs in <strong>constant time (O(1))</strong>.</li></ul><p><strong>🔹 What is a Method?</strong></p><p>A <strong>method</strong> is a function inside a struct or class that performs an operation.</p><p><strong>✅ Characteristics of Methods:</strong></p><ul><li>Can <strong>modify state</strong> (mutating for struct).</li><li>Can have <strong>side effects</strong>.</li><li>Can take <strong>parameters</strong>.</li></ul><p><strong>🔹 Example: Using a Method</strong></p><pre>struct Counter {<br>    var count = 0<br>    <br>    mutating func increment() {<br>        count += 1  // Modifies state<br>    }<br>}<br><br>var counter = Counter()<br>counter.increment()<br>print(counter.count) // Output: 1</pre><p><strong>🔹 Comparison Table: Computed Property vs. Method</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6YJpCpcv0Sx6jXrWWLc1hQ.png" /></figure><p><strong>🔹 When to Use a Computed Property vs. a Method?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdSzHyVcJyGGTfYA1klk0Q.png" /></figure><p><strong>🔹 Examples: When to Use Each?</strong></p><p><strong>✅ Good Use of a Computed Property</strong></p><pre>struct Square {<br>    var side: Double<br>    <br>    var area: Double {  // Computed Property<br>        return side * side<br>    }<br>}<br>let square = Square(side: 4)<br>print(square.area) // Output: 16</pre><p><strong>✅ Good Use of a Method</strong></p><pre>struct BankAccount {<br>    var balance: Double<br><br>    mutating func deposit(amount: Double) {<br>        balance += amount  // Modifies state<br>    }<br>}<br><br>var account = BankAccount(balance: 100)<br>account.deposit(amount: 50)<br>print(account.balance) // Output: 150</pre><p><strong>🚀 Final Thoughts</strong></p><ul><li>Use <strong>computed properties</strong> when calculating <strong>static</strong> values without side effects.</li><li>Use <strong>methods</strong> when an action <strong>modifies state</strong> or requires parameters.</li><li>If an operation <strong>takes too long</strong> (e.g., searching a list), <strong>use a method instead</strong> of a computed property.</li></ul><h3><strong>When to Use guard in Swift?</strong></h3><p>In Swift, guard is used to <strong>exit early</strong> from a function, loop, or scope when a certain condition is <strong>not met</strong>. It helps keep the <strong>main execution path</strong> clean by reducing <strong>nested if statements</strong>.</p><p><strong>🔹 Why Use guard?</strong></p><p>✅ <strong>Avoids Deep Nesting</strong> — Keeps the “happy path” of your code clear.<br>✅ <strong>Improves Readability</strong> — The main logic stays at the <strong>top level</strong>.<br>✅ <strong>Requires an else Block</strong> — Ensures that errors are handled properly.<br>✅ <strong>Unwraps Optionals</strong> — Works well with if let or guard let for safe optional handling.</p><p><strong>🔹 Basic Syntax of guard</strong></p><pre>guard condition else {<br>    // Handle failure case (exit early)<br>    return // or throw an error, break, continue, etc.<br>}</pre><p>🔹 If condition is <strong>false</strong>, the else block <strong>executes</strong>, and the function <strong>exits</strong>.</p><p><strong>🔹 Example 1: Using guard to Validate Input</strong></p><pre>func validateUserInput(name: String?) {<br>    guard let name = name, !name.isEmpty else {<br>        print(&quot;❌ Invalid name. Please enter a valid name.&quot;)<br>        return<br>    }<br>    <br>    print(&quot;✅ Welcome, \(name)!&quot;)<br>}</pre><pre>validateUserInput(name: nil) // Output: ❌ Invalid name. Please enter a valid name.<br>validateUserInput(name: &quot;John&quot;) // Output: ✅ Welcome, John!</pre><h3><strong>What is @autoclosure?</strong></h3><p>@autoclosure is a Swift attribute that <strong>automatically wraps an expression in a closure</strong>. It helps improve <strong>code readability</strong> by making function calls look more natural while <strong>delaying execution</strong> of potentially expensive computations.</p><p><strong>🔹 Why Use @autoclosure?</strong></p><p>✅ <strong>Improves Readability</strong> — No need to manually wrap expressions in {} when passing closures.<br>✅ <strong>Enables Lazy Evaluation</strong> — The expression is evaluated <strong>only if needed</strong>.<br>✅ <strong>Useful in Logging, Assertions, and Lazy Computations</strong> — Helps optimize performance when the result may not always be required.</p><p><strong>🔹 Basic Syntax of @autoclosure</strong></p><pre>func logMessage(_ message: @autoclosure () -&gt; String) {<br>    print(&quot;Log: \(message())&quot;)<br>}</pre><pre>logMessage(&quot;This is a log message&quot;) // No need to manually wrap in a closure</pre><p>🔹 <strong>Without @autoclosure</strong>, you would have to write:</p><pre>logMessage({ &quot;This is a log message&quot; })</pre><p>With @autoclosure, it simplifies to just:</p><pre>logMessage(&quot;This is a log message&quot;)</pre><p><strong>🔹 Example 1: Using @autoclosure for Lazy Evaluation</strong></p><p>Imagine we have a <strong>function that logs messages</strong> only if <strong>logging is enabled</strong>:</p><p><strong>✅ Using @autoclosure (Efficient)</strong></p><pre>var shouldLog = false<br>func log(_ message: @autoclosure () -&gt; String) {<br>    if shouldLog {<br>        print(message()) // Only executed if shouldLog is true<br>    }<br>}</pre><pre>log(&quot;This is an expensive log message&quot;) // Won’t execute if shouldLog is false</pre><p>🔹 <strong>Why is this useful?</strong></p><ul><li>The string “This is an expensive log message” <strong>is not computed</strong> unless shouldLog is true.</li><li>Helps <strong>improve performance</strong> by avoiding unnecessary computations.</li></ul><p><strong>❌ Without @autoclosure (Inefficient)</strong></p><pre>func log(_ message: String) {<br>    if shouldLog {<br>        print(message) // The message is always evaluated, even if not needed<br>    }<br>}</pre><pre>log(&quot;This is an expensive log message&quot;) // Evaluated even if not printed</pre><p>🔹 Here, the <strong>message is always evaluated</strong>, even when shouldLog is false. <strong>This wastes CPU time.</strong></p><p><strong>🔹 Example 2: Using @autoclosure in Assertions</strong></p><pre>func assertCondition(_ condition: @autoclosure () -&gt; Bool, message: String) {<br>    if !condition() {<br>        print(&quot;Assertion Failed: \(message)&quot;)<br>    }<br>}</pre><pre>let number = 5<br>assertCondition(number &gt; 10, message: &quot;Number is too small&quot;) // Will print assertion failure</pre><p>🔹 <strong>Why use @autoclosure here?</strong></p><ul><li>The expression number &gt; 10 <strong>is only evaluated</strong> when necessary.</li><li>If we used a normal closure { number &gt; 10 }, the function call <strong>would be less readable</strong>.</li></ul><p><strong>🔹 Comparison: @autoclosure vs. Normal Closures</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSas6aSbzkq6h4ABuCs7XA.png" /></figure><p><strong>🔹 When to Use @autoclosure?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyiSGrvNsrubFov4spH7DQ.png" /></figure><p><strong>🚀 Final Thoughts</strong></p><ul><li>@autoclosure <strong>improves readability</strong> and <strong>delays execution</strong>.</li><li>It is most useful in <strong>logging, assertions, and lazy computations</strong>.</li><li>Be <strong>careful when using it</strong>, as it <strong>hides closure behavior</strong>, which can make debugging harder.</li></ul><h3><strong>What is Dependency Injection (DI)?</strong></h3><p><strong>🔹 Why Use DI?<br></strong>✅ <strong>Modular Code<br></strong>✅ <strong>Easier Unit Testing<br></strong>✅ <strong>Decoupled Dependencies</strong></p><p><strong>❌ Without DI (Tightly Coupled)</strong></p><pre>class ViewModel {<br>    let service = Service() // Hardcoded dependency ❌<br>}</pre><p><strong>✅ With DI (Constructor Injection)</strong></p><pre>class ViewModel {<br>    let service: ServiceProtocol<br>    init(service: ServiceProtocol) {<br>        self.service = service<br>    }<br>}</pre><p><strong>🔹 Recap<br></strong>Dependency Injection <strong>improves modularity</strong>, <strong>testability</strong>, and <strong>maintainability</strong> in Swift apps.</p><h3><strong>What is a Variadic Function in Swift?</strong></h3><p>A <strong>variadic function</strong> is a function that <strong>accepts a variable number of arguments</strong> of the same type. Instead of specifying a fixed number of parameters, Swift allows <strong>zero or more</strong> values to be passed using a <strong>variadic parameter</strong>.</p><p><strong>🔹 Syntax of a Variadic Function<br></strong>In Swift, we define a variadic function by <strong>adding … after the parameter type</strong>.</p><p><strong>✅ Basic Example</strong></p><pre>func sum(numbers: Int...) -&gt; Int {<br>    return numbers.reduce(0, +)<br>}<br>print(sum(numbers: 1, 2, 3, 4, 5)) // Output: 15<br>print(sum(numbers: 10, 20)) // Output: 30<br>print(sum(numbers: )) // Output: 0 (Works even with zero arguments!)</pre><p><strong>🔹 Comparison: Variadic Function vs. Regular Function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLK7Z1a-9YGx6-uL1yCHvw.png" /></figure><p><strong>🔹 Use Cases of Variadic Functions</strong></p><p>✅ <strong>Summing Numbers</strong></p><pre>func sum(_ numbers: Int...) -&gt; Int {<br>    return numbers.reduce(0, +)<br>}</pre><p>✅ <strong>Logging Messages with Different Levels</strong></p><pre>func logMessage(level: String, messages: String...) {<br>    for message in messages {<br>        print(&quot;[\(level)] \(message)&quot;)<br>    }<br>}<br>logMessage(level: &quot;INFO&quot;, messages: &quot;App started&quot;, &quot;User logged in&quot;)<br>// Output:<br>// [INFO] App started<br>// [INFO] User logged in</pre><p>✅ <strong>String Formatting</strong></p><pre>func joinWords(separator: String, words: String...) -&gt; String {<br>    return words.joined(separator: separator)<br>}<br>print(joinWords(separator: &quot;-&quot;, words: &quot;Swift&quot;, &quot;iOS&quot;, &quot;Development&quot;))<br>// Output: Swift-iOS-Development</pre><p><strong>🚀 Final Thoughts</strong></p><ul><li><strong>Variadic functions</strong> allow passing <strong>a flexible number of parameters</strong> of the same type.</li><li>They are <strong>useful for operations like summing numbers, joining strings, and logging messages</strong>.</li><li>A function <strong>can only have one variadic parameter, and it must be last</strong>.</li></ul><p>💡 <strong>Swift’s variadic functions provide flexibility without sacrificing readability and efficiency!</strong> 🎯</p><h3><strong>What Are Opaque Return Types in Swift?</strong></h3><p>Opaque return types, introduced in <strong>Swift 5.1</strong>, allow functions and properties to <strong>return a specific type without revealing the exact type</strong>. Instead of exposing a concrete return type, Swift enforces a <strong>consistent underlying type</strong> while keeping it hidden from the caller.</p><p>This is achieved using the <strong>some keyword</strong> before the return type.</p><p><strong>🔹 Why Use Opaque Return Types?</strong></p><p>✅ <strong>Encapsulation</strong> — Hides the concrete type while ensuring type safety.<br>✅ <strong>Flexibility</strong> — Allows returning different types conforming to the same protocol.<br>✅ <strong>Improved Readability</strong> — Simplifies function signatures without exposing unnecessary details.<br>✅ <strong>Better Performance</strong> — Compiler optimizations work more efficiently compared to protocol-based dynamic dispatch.</p><pre>func makeShape() -&gt; some Shape {<br>    Circle()<br>}</pre><ul><li>The function <strong>makeShape()</strong> returns <strong>some Shape</strong>, meaning it <strong>returns a concrete type</strong> that conforms to the Shape protocol.</li><li>The caller <strong>does not know</strong> if it’s returning Circle, Rectangle, etc., but Swift enforces <strong>a single, consistent type</strong>.</li></ul><p><strong>Opaque Return Type vs. Protocol Return Type</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*171W8CHCyShXZ__qStQ5yQ.png" /></figure><p><strong>Opaque Return Type in Functions</strong></p><pre>protocol Shape {<br>    func area() -&gt; Double<br>}<br><br>struct Circle: Shape {<br>    var radius: Double<br>    func area() -&gt; Double { return .pi * radius * radius }<br>}<br><br>struct Square: Shape {<br>    var side: Double<br>    func area() -&gt; Double { return side * side }<br>}<br><br>// Function using opaque return type<br>func getShape() -&gt; some Shape {<br>    return Circle(radius: 5)<br>}<br><br>let shape = getShape()<br>print(shape.area()) // ✅ Works, but we don&#39;t know the concrete type</pre><p><strong>Opaque Return Type in Properties</strong></p><pre>struct ShapeFactory {<br>    static var defaultShape: some Shape {<br>        Circle(radius: 10)<br>    }<br>}<br><br>let shape = ShapeFactory.defaultShape<br>print(shape.area()) // ✅ Works, type is hidden</pre><p><strong>Why use it in properties?</strong></p><ul><li>Helps in frameworks or APIs where we <strong>don’t want to expose implementation details</strong>.</li></ul><p><strong>Opaque Return Type vs. Protocol Return Type</strong></p><p><strong>❌ Using Protocol Return Type (Less Efficient)</strong></p><pre>func makeShape(usingCircle: Bool) -&gt; Shape {<br>    return usingCircle ? Circle(radius: 5) : Square(side: 4) // ✅ Works<br>}</pre><ul><li>Allows returning <strong>different types</strong> (Circle or Square), but…</li><li>Uses <strong>dynamic dispatch</strong>, <strong>hurting performance</strong>.</li></ul><p><strong>✅ Using Opaque Return Type (More Efficient)</strong></p><pre>func makeShape() -&gt; some Shape {<br>    Circle(radius: 5) // ✅ Always returns the same type<br>}</pre><ul><li>Ensures <strong>static dispatch</strong> (faster).</li><li>Swift <strong>optimizes performance</strong> since the type is <strong>known at compile-time</strong>.</li></ul><p><strong>When to Use Opaque Return Types?<br></strong>✅ When returning a <strong>specific type that conforms to a protocol</strong>, but you <strong>don’t want to expose</strong> the concrete type.<br>✅ When <strong>performance is a concern</strong>, as <strong>opaque return types use static dispatch</strong> instead of dynamic dispatch.<br>✅ When building <strong>APIs or libraries</strong> that require implementation <strong>hiding and abstraction</strong>.</p><p><strong>🚀 Final Thoughts</strong></p><ul><li>Opaque return types (some Type) <strong>improve abstraction</strong> while maintaining <strong>type safety</strong>.</li><li>They are <strong>faster than protocol return types</strong> due to <strong>static dispatch</strong>.</li><li>However, <strong>opaque return types cannot return multiple different conforming types</strong>.</li><li><strong>Use some when you need abstraction without sacrificing performance!</strong></li></ul><h3><strong>What is a Singleton?</strong></h3><p>A <strong>Singleton</strong> is a design pattern that ensures <strong>only one instance</strong> of a class is created and provides a <strong>global access point</strong> to that instance. This is useful when exactly one object is needed to coordinate actions across the system, such as a <strong>shared database manager, network manager, or user session handler</strong>.</p><p>In Swift, a Singleton is typically implemented using a <strong>static instance</strong> inside the class.</p><pre>class DatabaseManager {<br>    static let shared = DatabaseManager() // Singleton instance, The static keyword ensures it belongs to the class rather than an instance.<br>    <br>    private init() { // Prevents direct instantiation of the class from outside.<br>        print(&quot;DatabaseManager initialized&quot;) <br>    }<br>    <br>    func fetchData() {<br>        print(&quot;Fetching data from database...&quot;)<br>    }<br>}<br><br>// Usage<br>let db1 = DatabaseManager.shared<br>let db2 = DatabaseManager.shared<br><br>db1.fetchData()  // Output: Fetching data from database...<br>print(db1 === db2)  // Output: true (both instances are the same)</pre><p><strong>Use Cases for Singleton</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*nYeOr-yADP_ZS0PmIu_wlQ.png" /></figure><p><strong>Pros &amp; Cons of Singleton Pattern</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5INZF20xS4CEqwMNUim3yg.png" /></figure><p><strong>How to Make a Singleton Thread-Safe in Swift?</strong></p><p>When working in a multithreaded environment, ensuring that a <strong>singleton instance</strong> is <strong>thread-safe</strong> is crucial. In Swift, we can achieve this using DispatchQueue. Below, we explore <strong>two efficient approaches</strong> for making a singleton thread-safe:</p><ul><li><strong>Using a Dispatch Queue with sync (Simple Approach)</strong></li><li><strong>Using a Dispatch Queue with .barrier (Optimized Approach for Read-Heavy Operations)</strong></li></ul><p><strong>Approach 1: Thread-Safe Singleton Using a Serial Dispatch Queue</strong></p><p>This method ensures that only <strong>one thread accesses the critical section at a time</strong>.</p><pre>class ThreadSafeSingleton {<br>    static let shared = ThreadSafeSingleton()  // Singleton instance<br>    <br>    private init() { }  // Private initializer to prevent multiple instances<br>    <br>    private let queue = DispatchQueue(label: &quot;SingletonQueue&quot;, attributes: .concurrent)<br><br>    func safeMethod() {<br>        queue.sync {<br>            print(&quot;Thread-safe operation&quot;)<br>        }<br>    }<br>}</pre><p><strong>How It Works?</strong></p><ul><li>The singleton instance is created using static let shared.</li><li>The initializer is <strong>private</strong> to <strong>restrict external instantiation</strong>.</li><li>A <strong>concurrent dispatch queue</strong> is used to handle synchronization.</li><li>The safeMethod() ensures that <strong>only one thread executes at a time</strong> using sync.</li></ul><p><strong>Approach 2: Thread-Safe Singleton Using a Concurrent Queue with Dispatch Barrier</strong></p><p>For <strong>read-heavy</strong> operations where multiple threads should be able to <strong>read simultaneously</strong> but <strong>writes should be exclusive</strong>, we use .barrier.</p><pre>class ThreadSafeSingleton {<br>    static let shared = ThreadSafeSingleton()  // Singleton instance<br>    <br>    private init() { }  // Private initializer to enforce singleton pattern<br>    <br>    private let queue = DispatchQueue(label: &quot;LoggerQueue&quot;, attributes: .concurrent)<br>    private var logDict: [String: Any] = [:]  // Shared resource<br><br>    func writeToLog(key: String, value: Any) {<br>        queue.async(flags: .barrier) { [weak self] in<br>            self?.logDict[key] = value<br>            print(&quot;Written: \(key) -&gt; \(value)&quot;)<br>        }<br>    }<br>    <br>    func readFromLog(key: String) -&gt; Any? {<br>        queue.sync {<br>            return logDict[key]<br>        }<br>    }<br>}</pre><p><strong>How It Works?</strong></p><ul><li><strong>Reads are concurrent</strong>, meaning multiple threads can <strong>read without blocking</strong>.</li><li><strong>Writes use .barrier</strong>, ensuring that <strong>only one thread</strong> writes at a time while <strong>blocking other reads and writes</strong>.</li><li>The logDict dictionary represents <strong>shared mutable data</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QedGxZMjYuL6NW449DJwGw.png" /></figure><p>For most cases, a simple thread-safe singleton <strong>using sync</strong> is enough. However, if you need <strong>efficient read-heavy access with occasional writes</strong>, use <strong>.barrier with a concurrent queue</strong>.</p><p><strong>🎯 Final Thoughts</strong></p><p>The <strong>Singleton pattern</strong> is a <strong>powerful tool</strong> in Swift but <strong>should be used wisely</strong>. It’s ideal for <strong>global services</strong> like network managers and logging systems but can lead to <strong>tight coupling</strong> and <strong>testing challenges</strong> if overused.</p><h3>Structs Vs Classes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYjUrl3VONDoViQ7IcDi4A.png" /></figure><p><strong>Connect with Me on LinkedIn!</strong></p><p>If you found this guide helpful, feel free to connect with me on LinkedIn! Let’s grow, learn, and collaborate together.</p><blockquote><em>🔗 </em><a href="https://www.linkedin.com/in/ahilendran/"><em>Follow me on LinkedIn</em></a></blockquote><p>Your feedback and thoughts are always welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c262ab2e9676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Senior iOS Developer Interview Questions 2025: SwiftUI Focus (Part 1)]]></title>
            <link>https://medium.com/@eahilendran/ios-developer-interview-question-2025-part-1-swift-20d2517f1e32?source=rss-8d8df9c5eb5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/20d2517f1e32</guid>
            <dc:creator><![CDATA[Ahil NS]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 02:09:29 GMT</pubDate>
            <atom:updated>2025-02-18T03:52:56.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top Senior iOS Developer Interview Questions 2025: SwiftUI (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0aSuE5ZJxM4XXQEcchXVw.png" /></figure><p>If you’re preparing for an <strong>iOS interview</strong>, understanding Swift’s core concepts is crucial. In this article, we’ll break down some of the <strong>most commonly asked iOS interview questions</strong>, with <strong>clear explanations, examples, and comparison tables</strong> to make learning easier.</p><p>Check out <a href="https://medium.com/@eahilendran/top-senior-ios-developer-interview-questions-2025-swift-focus-part-2-c262ab2e9676"><strong>Top Senior iOS Developer Interview Questions 2025: Swift Focus (Part 2)</strong></a></p><h3><strong>Why does SwiftUI use structs for views?</strong></h3><p>1. <strong>Performance Efficiency</strong>: Structs are lightweight and faster to create compared to classes. In UIKit, every view inherits numerous properties and methods from UIView, leading to potential overhead. In contrast, SwiftUI views as structs contain only explicitly defined properties, enhancing performance.</p><p>2. <strong>Immutability and Predictability</strong>: Structs are immutable by default, meaning their instances cannot be altered after creation. This immutability aligns with SwiftUI’s declarative approach, where views are a function of state. When the state changes, SwiftUI creates new instances of view structs, ensuring a predictable and consistent UI without unintended side effects.</p><p>3. <strong>Value Semantics</strong>: Structs are passed by value, not by reference. This characteristic prevents issues like retain cycles and reference counting, leading to fewer memory leaks and more straightforward memory management. Each modification results in a new copy, ensuring that changes in one part of the app don’t inadvertently affect others.</p><p>4. <strong>Functional Design Encouragement</strong>: By using structs, SwiftUI encourages a more functional design approach. Views become simple, inert entities that convert data into UI, rather than complex objects that can grow uncontrollably. This design promotes cleaner state management and reduces the likelihood of unintended side effects.</p><h3><strong>How does SwiftUI use the diffing algorithm to optimize UI updates?</strong></h3><p>SwiftUI uses a <strong>diffing algorithm</strong> to compare the previous and current states of the UI and <strong>only updates the changed parts</strong>. This is called <strong>“state-driven rendering.”</strong></p><p><strong>How It Works:</strong></p><ul><li>SwiftUI <strong>recalculates</strong> the body property every time a @State, @ObservedObject, or @EnvironmentObject value changes.</li><li>Instead of rebuilding the entire UI, SwiftUI <strong>compares the new and old view trees</strong>.</li><li>The <strong>diffing engine</strong> finds the <strong>minimum number of changes</strong> needed and applies them efficiently.</li></ul><h3>How does SwiftUI’s declarative syntax differ from UIKit’s imperative approach?</h3><p><strong>Declarative Syntax in SwiftUI:</strong></p><p>In SwiftUI, developers describe the desired UI state, and the framework manages the rendering and updates. This approach focuses on <em>what</em> the UI should display, allowing SwiftUI to handle the <em>how</em>. For example, to create a button that toggles its label between “Active” and “Inactive”:</p><pre>struct ContentView: View {<br>    @State private var isActive = false<br><br>    var body: some View {<br>        Button(action: {<br>            isActive.toggle()<br>        }) {<br>            Text(isActive ? &quot;Active&quot; : &quot;Inactive&quot;)<br>        }<br>    }<br>}</pre><p>Here, the UI automatically reflects the current state of isActive, and any changes to this state prompt SwiftUI to update the relevant parts of the interface.</p><p><strong>Imperative Approach in UIKit:</strong></p><p>UIKit requires developers to explicitly define each step of the UI’s behavior, focusing on <em>how</em> to achieve the desired outcome. This involves manually managing the state and ensuring the UI stays in sync. The equivalent button in UIKit would be:</p><pre>class ViewController: UIViewController {<br>    var isActive = false<br>    let button = UIButton(type: .system)<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        button.setTitle(&quot;Inactive&quot;, for: .normal)<br>        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)<br>        view.addSubview(button)<br>        // Layout code for button positioning goes here<br>    }<br><br>    @objc func buttonTapped() {<br>        isActive.toggle()<br>        button.setTitle(isActive ? &quot;Active&quot; : &quot;Inactive&quot;, for: .normal)<br>    }<br>}</pre><p>In this scenario, the developer is responsible for updating the button’s title and managing its layout, ensuring the UI accurately reflects the current state.</p><p><strong>Key Differences:</strong></p><ul><li><strong>State Management:</strong> SwiftUI automatically updates the UI in response to state changes, reducing the potential for inconsistencies. In contrast, UIKit requires manual updates to synchronize the UI with the underlying state.</li><li><strong>Code Conciseness:</strong> SwiftUI’s declarative nature often results in more concise and readable code, as it abstracts much of the boilerplate involved in UI updates. UIKit’s imperative style can lead to more verbose code due to explicit state and UI management.</li></ul><h3>Describe the lifecycle of a SwiftUI view.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxdYTV7pf0dDVaksdh40YA.png" /></figure><h4><strong>Initialization</strong></h4><p><strong>View Creation:</strong> SwiftUI views are lightweight structures, often value types (structs), that describe the UI’s appearance and behavior. When a view is initialized, it’s not yet connected to any state or rendered onscreen.</p><h4>Appearing</h4><p><strong>Appearing</strong> means inserting a view into a view graph. In this phase, a view is initialized, subscribed to the state, and rendered for the first time.</p><p><strong>onAppear Modifier:</strong> Once the view becomes part of the view hierarchy and is about to appear onscreen, SwiftUI calls the onAppear modifier. This is an opportunity to initiate tasks such as data loading or starting animations.</p><ol><li>At the time of initialization, a view is not connected to the state. This makes view construction cheap since the whole view hierarchy is built upfront.</li><li>After the initialization, and before the body is computed, a view gets connected to the state.</li><li>View body is called for the first time.</li><li>Update view graph and render changes.</li><li>The onAppear() method is called top-down: from parent to child view.</li></ol><h4>Updating</h4><p><strong>State Changes:</strong> When a view’s state changes — either through user interaction or external events — SwiftUI re-evaluates the view’s body to reflect these changes. It’s essential to ensure that the body property remains a pure function of the state, free from side effects.</p><p><strong>Updating</strong> is performed in response to an external event or state mutation.</p><ol><li>A user action causes state change or SwiftUI detects data emitted by a publisher observed via View.onReceive().</li><li>A view, which owns a mutated state or which received an external event, and all of its children, is compared against its previous snapshot. At this point, we can provide our custom definition of view equality by conforming our view to the Equatable protocol and wrapping it into EquatableView.</li><li>SwiftUI invalidates the views that have changed.</li><li>Update view graph and render invalidated views. All the updates flow down through the view hierarchy.</li></ol><p><em>Note: only views that are connected to the state can provide custom equality implementation. Views not connected to the state are always re-rendered.</em></p><h4>Disappearing</h4><p><strong>Disappearing</strong> means removing a view from the hierarchy.</p><p><strong>onDisappear Modifier:</strong> When a view is removed from the hierarchy, SwiftUI invokes the onDisappear modifier. This is the appropriate place to cancel network requests, stop timers, or perform other cleanup tasks.</p><p>The onDisappear() method is called after a view has been removed from the hierarchy. Similarly to onAppear(), onDisappear() is called top-down: from parent to child view.</p><h3>SwiftUI View vs UIView</h3><p>SwiftUI’s View and UIKit’s UIView are both fundamental components for constructing user interfaces in iOS applications, but they differ significantly in their design paradigms, implementation, and usage.</p><ul><li><strong>SwiftUI (View):</strong> Embraces a declarative approach, allowing developers to define what the UI should look like and how it behaves by declaring its state and layout. The framework manages the rendering and updates based on state changes.</li><li><strong>UIKit (UIView):</strong> Follows an imperative paradigm, where developers explicitly create and manage the UI components and their lifecycle, often involving direct manipulation and handling of view hierarchies.</li></ul><p><strong>Implementation and Usage:</strong></p><ul><li><strong>SwiftUI (View):</strong> Views are defined as structs conforming to the View protocol. They are value types, meaning they are lightweight and describe the UI’s appearance and behavior without holding mutable state.</li></ul><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, SwiftUI!&quot;)<br>    }<br>}</pre><ul><li><strong>UIKit (UIView):</strong> UIView is a class, making it a reference type. Developers instantiate and configure views, adding them to the view hierarchy and managing their state and layout manually.</li></ul><pre>class CustomView: UIView {<br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        setupView()<br>    }<br><br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        setupView()<br>    }<br><br>    private func setupView() {<br>        let label = UILabel()<br>        label.text = &quot;Hello, UIKit!&quot;<br>        label.textAlignment = .center<br>        label.frame = self.bounds<br>        addSubview(label)<br>    }<br>}</pre><p><strong>Interoperability:</strong></p><p>While SwiftUI and UIKit are distinct frameworks, they can interoperate to leverage existing codebases or utilize specific functionalities:</p><ul><li><strong>Using UIView in SwiftUI:</strong> To incorporate a UIKit view within SwiftUI, conform to the UIViewRepresentable protocol, which bridges UIKit components into SwiftUI.</li></ul><pre>import SwiftUI<br>import UIKit<br><br>struct UIKitLabel: UIViewRepresentable {<br>    func makeUIView(context: Context) -&gt; UILabel {<br>        let label = UILabel()<br>        label.text = &quot;Hello from UIKit&quot;<br>        label.textAlignment = .center<br>        return label<br>    }<br><br>    func updateUIView(_ uiView: UILabel, context: Context) {<br>        // Update the UILabel if needed<br>    }<br>}</pre><ul><li><strong>Using SwiftUI in UIKit:</strong> To embed a SwiftUI view within a UIKit view controller, utilize UIHostingController, which acts as a bridge by hosting a SwiftUI view.</li></ul><pre>import SwiftUI<br>import UIKit<br><br>let swiftUIView = ContentView()<br>let hostingController = UIHostingController(rootView: swiftUIView)</pre><h3>StateObject</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbHZ7GAcdg496TMIeQcPQA.png" /></figure><p>In SwiftUI, @StateObject is a property wrapper introduced to manage the lifecycle of reference-type data within a view. It ensures that an observable object, conforming to the ObservableObject protocol, is created and maintained by the view, allowing the view to respond to changes in the object’s state.</p><p><strong>Key Points:</strong></p><ul><li><strong>Ownership and Initialization:</strong> Use @StateObject when the view is responsible for creating and owning the observable object. This ensures that the object persists for the lifetime of the view and is not recreated unnecessarily during view updates.</li><li><strong>State Management:</strong> When properties within the observable object are marked with @Published, any changes to these properties will automatically trigger the view to refresh, reflecting the updated state.</li></ul><p>In general, we use @StateObject to set some kind of ViewModel for our screen. That is, we pair it with a class that obeys the ObservableObject protocol. It works very similarly to @State, with one exception: it is created after the first initialization of the structure. That is, while @State could somehow be passed to init to put the first value, @StateObject won&#39;t work. It will be deleted from memory after the initializer is called and will be created again.</p><h3>State</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpLzKrUKqTh0gsDqSO4lQA.png" /></figure><p>In SwiftUI, the @State property wrapper is used to manage mutable state within a view. It allows a view to respond to changes in its data by automatically re-rendering when that data changes.</p><p><strong>Key Characteristics of @State:</strong></p><ul><li><strong>Local State Management:</strong> @State is designed for data that is owned and used exclusively by a single view. It’s ideal for simple properties like strings, numbers, or other value types that don’t need to be shared across multiple views.</li><li><strong>Automatic View Updates:</strong> When a @State property’s value changes, SwiftUI detects the change and schedules a re-render of the view to reflect the new state. This ensures the UI stays in sync with its underlying data.</li><li><strong>Struct Compatibility:</strong> Since SwiftUI views are structs (which are value types and immutable by default), @State provides a way to introduce mutability, allowing views to modify their own state.</li></ul><h3><strong>Completion Handler vs Task in Swift</strong></h3><p>Swift’s concurrency model has evolved with Task and async/await, replacing traditional <strong>completion handlers</strong> for handling asynchronous operations. Here’s a concise comparison.</p><p>If targeting iOS 15+, prefer <strong>async/await</strong> for cleaner and more maintainable code. For older versions, completion handlers remain necessary.</p><h4>Completion Handler (Old Approach)</h4><p>A <strong>callback-based</strong> approach where a function executes asynchronously and invokes a closure upon completion.</p><pre>func fetchData(url: String, completion: @escaping (String?, Error?) -&gt; Void) {<br>    DispatchQueue.global().async {<br>        completion(&quot;Data from \(url)&quot;, nil)<br>    }<br>}</pre><p>✅ Works on all iOS versions<br>❌ Leads to nested closures, making code harder to read</p><h4>Task-Based Concurrency (Modern Approach)</h4><p>Swift’s async/await improves readability and <strong>structured concurrency</strong>.</p><pre>func fetchData(url: String) async -&gt; String {<br>    return &quot;Data from \(url)&quot;<br>}<br><br>Task {<br>    let data = await fetchData(url: &quot;https://example.com&quot;)<br>    print(data)<br>}</pre><p>✅ More readable, structured concurrency<br>✅ Automatic memory management, built-in error handling <br>❌ Requires <strong>Swift 5.5+</strong> (iOS 15+)</p><h4>Key Differences</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYeDzPBPUG5FM54Jdv914w.png" /></figure><h4>Convert Completion Handler to Async/Await</h4><pre>func fetchData(url: String) async -&gt; String {<br>    return await withCheckedContinuation { continuation in<br>        fetchData(url: url) { data, _ in<br>            continuation.resume(returning: data ?? &quot;&quot;)<br>        }<br>    }<br>}</pre><h3>How does SwiftUI handle orientation changes?</h3><p>SwiftUI doesn’t provide a built-in mechanism to detect device orientation changes directly. However, you can achieve this by integrating UIKit’s UIDevice notifications into your SwiftUI views. Here’s how you can implement this:</p><pre>import SwiftUI<br><br>// Custom view modifier to track rotation and call our action<br>struct DeviceRotationViewModifier: ViewModifier {<br>    let action: (UIDeviceOrientation) -&gt; Void<br><br>    func body(content: Content) -&gt; some View {<br>        content<br>            .onAppear()<br>            .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in<br>                let currentOrientation = UIDevice.current.orientation<br>                if currentOrientation.isValidInterfaceOrientation {<br>                    action(currentOrientation)<br>                }<br>            }<br>    }<br>}<br><br>// View extension to make the modifier easier to use<br>extension View {<br>    func onRotate(perform action: @escaping (UIDeviceOrientation) -&gt; Void) -&gt; some View {<br>        self.modifier(DeviceRotationViewModifier(action: action))<br>    }<br>}<br><br>// Example view demonstrating the solution<br>struct ContentView: View {<br>    @State private var orientation = UIDeviceOrientation.unknown<br><br>    var body: some View {<br>        Group {<br>            if orientation.isPortrait {<br>                Text(&quot;Portrait&quot;)<br>            } else if orientation.isLandscape {<br>                Text(&quot;Landscape&quot;)<br>            } else if orientation.isFlat {<br>                Text(&quot;Flat&quot;)<br>            } else {<br>                Text(&quot;Unknown&quot;)<br>            }<br>        }<br>        .onAppear {<br>            // Fetch the current interface orientation on appear<br>            if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {<br>                let interfaceOrientation = scene.interfaceOrientation<br>                switch interfaceOrientation {<br>                case .portrait:<br>                    orientation = .portrait<br>                case .portraitUpsideDown:<br>                    orientation = .portraitUpsideDown<br>                case .landscapeLeft:<br>                    orientation = .landscapeLeft<br>                case .landscapeRight:<br>                    orientation = .landscapeRight<br>                default:<br>                    orientation = .unknown<br>                }<br>            }<br>        }<br>        .onRotate { newOrientation in<br>            orientation = newOrientation<br>        }<br>    }<br>}</pre><h3><strong>What is the difference between @State, @Binding, @ObservedObject, and @EnvironmentObject?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzGVpr-XG1qbs5r28iNrXQ.png" /></figure><h3>What’s difference between @ObservedObject and @StateObject?</h3><p>Both @ObservedObject and @StateObject are used to <strong>track and manage external state</strong> in SwiftUI, but they behave differently in terms of <strong>ownership and lifecycle management</strong>.</p><ul><li>Use @StateObject when a view creates and owns an observable object.</li><li>Use @ObservedObject when passing an already existing observable object to a subview.</li><li>If a view is recreated frequently, @ObservedObject might cause data loss — use @StateObject instead.</li><li>Combine them for efficient data sharing between parent and child views.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUVkge0TAz3xEvlwsNqvkA.png" /></figure><p><strong>@ObservedObject (Parent-Owned State) — Problem: Losing Data on Re-render</strong></p><pre>class CounterModel: ObservableObject {<br>    @Published var count = 0<br>}<br><br>struct ParentView: View {<br>    @State private var counter = CounterModel() // Parent owns it<br><br>    var body: some View {<br>        ChildView(counter: counter) // Passing down<br>    }<br>}<br><br>struct ChildView: View {<br>    @ObservedObject var counter: CounterModel<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(counter.count)&quot;)<br>            Button(&quot;Increment&quot;) { counter.count += 1 }<br>        }<br>    }<br>}</pre><p>📌 <strong>How It Works:<br>- </strong>ParentView owns the CounterModel and passes it to ChildView.<br>- ChildView <strong>does not own</strong> the model; it just observes changes.</p><p>📌 <strong>What Happens on Re-render?<br>- </strong>If ParentView <strong>recreates</strong> CounterModel, ChildView will get a <strong>new instance</strong>, <strong>losing previous data</strong>.</p><p><strong>@StateObject (View-Owned State) — Retaining Data Across Re-renders</strong></p><pre>struct StateObjectExample: View {<br>    @StateObject private var counter = CounterModel() // View owns the state<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(counter.count)&quot;)<br>            Button(&quot;Increment&quot;) { counter.count += 1 }<br>        }<br>    }<br>}</pre><p>📌 <strong>How It Works:<br>- </strong>StateObjectExample <strong>creates</strong> and <strong>owns</strong> CounterModel.<br>- Even if the view <strong>re-renders</strong>, counter <strong>remains unchanged</strong>.</p><p>📌 <strong>Why is This Better?<br>- </strong>@StateObject <strong>ensures the object is created only once</strong>, so data is preserved across updates.</p><p><strong>When Should You Use @ObservedObject vs. @StateObject?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*kXg5n9Kuv4UIT3xEM-7GNA.png" /></figure><p><strong>Using @StateObject and @ObservedObject Together</strong></p><p>In many real-world apps, you <strong>combine both</strong> @StateObject and @ObservedObject.</p><p>Example: Parent Uses @StateObject, Child Uses @ObservedObject</p><pre>struct ParentView: View {<br>    @StateObject private var counter = CounterModel() // View owns the object<br><br>    var body: some View {<br>        ChildView(counter: counter) // Pass it down<br>    }<br>}<br><br>struct ChildView: View {<br>    @ObservedObject var counter: CounterModel // Observes updates<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(counter.count)&quot;)<br>            Button(&quot;Increment&quot;) { counter.count += 1 }<br>        }<br>    }<br>}</pre><p>📌 <strong>Why Use Both?<br>- </strong>The <strong>parent owns the state</strong> (@StateObject).<br>- The <strong>child only observes the state</strong> (@ObservedObject).<br>- This prevents counter from being reset when ChildView re-renders.</p><h3><strong>Explain the difference between .task {} and Task {}</strong></h3><p>In SwiftUI, both .task {} and Task {} are utilized to perform asynchronous operations, but they differ in their integration with the view lifecycle and their management of tasks.</p><p><strong>Key Differences:</strong></p><ul><li><strong>Lifecycle Management:</strong> .task {} is automatically managed by SwiftUI, starting and canceling tasks in sync with the view’s lifecycle. In contrast, Task {} requires manual management of the task’s lifecycle.</li><li><strong>Use Case Suitability:</strong> Use .task {} when the asynchronous operation is closely tied to the view’s presence. Opt for Task {} when the operation is independent of the view’s lifecycle or when initiating tasks outside of a view context.</li></ul><p><strong>.task {} Modifier:</strong></p><ul><li><strong>Lifecycle Integration:</strong> The .task {} modifier attaches an asynchronous task directly to a SwiftUI view. This task begins execution when the view appears and is automatically canceled when the view disappears, ensuring that resources are managed efficiently in line with the view’s presence on the screen.</li><li><strong>Automatic Cancellation:</strong> By binding the task to the view’s lifecycle, SwiftUI ensures that any ongoing operations are halted if the view is no longer visible, preventing unnecessary background activity.</li></ul><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @State private var data: String = &quot;Loading...&quot;<br><br>    var body: some View {<br>        Text(data)<br>            .task {<br>                await fetchData()<br>            }<br>    }<br><br>    func fetchData() async {<br>        // Simulate a network request<br>        try? await Task.sleep(nanoseconds: 1_000_000_000)<br>        data = &quot;Data loaded&quot;<br>    }<br>}</pre><p><strong>Task {} Initializer:</strong></p><ul><li><strong>Manual Task Creation:</strong> The Task {} initializer is used to create and start a new asynchronous task independently of the SwiftUI view lifecycle. These tasks are not automatically tied to any view’s appearance or disappearance.</li><li><strong>Explicit Management:</strong> Since Task {} does not integrate with the view lifecycle, developers are responsible for managing the task’s cancellation and ensuring it doesn’t continue running unnecessarily if the related view disappears.</li></ul><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @State private var data: String = &quot;Loading...&quot;<br><br>    var body: some View {<br>        Text(data)<br>            .onAppear {<br>                Task {<br>                    await fetchData()<br>                }<br>            }<br>    }<br><br>    func fetchData() async {<br>        // Simulate a network request<br>        try? await Task.sleep(nanoseconds: 1_000_000_000)<br>        data = &quot;Data loaded&quot;<br>    }<br>}</pre><h3>How would you explain SwiftUI’s environment to a new developer?</h3><p>SwiftUI’s <strong>environment</strong> is a system that allows data to be shared across multiple views <strong>without needing to pass it explicitly</strong>. It helps manage <strong>global app-wide data</strong> efficiently.</p><p>Think of it as a <strong>context or global store</strong> where values (like theme settings, user preferences, or app-wide objects) are stored and accessed by multiple views without cluttering the view hierarchy with direct dependencies.</p><p><strong>Key Components of SwiftUI’s Environment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2a0lVpLYCZf6jTUtJAH1Q.png" /></figure><p><strong>When to Use SwiftUI’s Environment?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*z6pxzo8IyReHMbMQ4KtLig.png" /></figure><h3><strong>Difference Between a View’s Initializer and onAppear() in SwiftUI</strong></h3><p>• Use <strong>init()</strong> for <strong>one-time setup</strong> (initializing properties).<br>• Use <strong>onAppear()</strong> for <strong>tasks that should happen every time the view is shown</strong> (data fetching, animations, logging).<br>• onAppear() is <strong>tied to the UI lifecycle</strong>, while init() is tied to <strong>the instance creation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2n9gjpY1x2A1elx308OZwA.png" /></figure><h3><strong>What is @ViewBuilder and how it Contributes to Performance in SwiftUI</strong></h3><p>@ViewBuilder is a <strong>SwiftUI result builder</strong> that allows multiple views to be grouped together in a single return statement. It improves <strong>readability</strong>, <strong>code organization</strong>, and <strong>performance</strong> by optimizing SwiftUI’s rendering system.</p><ol><li><strong>How @ViewBuilder Works</strong></li></ol><p>When returning multiple views from a function or computed property, @ViewBuilder <strong>automatically constructs a View hierarchy</strong> without requiring explicit VStack or Group.</p><p><strong>Example Without @ViewBuilder</strong></p><h4>• <strong>Requires VStack</strong> to group multiple views.</h4><pre>struct ContentView: View {<br>    var body: some View {<br>        VStack {<br>            Text(&quot;Hello, SwiftUI!&quot;)<br>            Text(&quot;This is without @ViewBuilder&quot;)<br>        }<br>    }<br>}</pre><p><strong>Example With @ViewBuilder</strong></p><p><strong>No need for an explicit VStack</strong> → @ViewBuilder automatically groups multiple views.</p><pre>struct CustomView: View {<br>    @ViewBuilder var body: some View {<br>        Text(&quot;Hello, SwiftUI!&quot;)<br>        Text(&quot;This is with @ViewBuilder&quot;)<br>    }<br>}</pre><p><strong>2. How @ViewBuilder Improves Performance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VaZ1BnVzR-NDtYdOjUDUA.png" /></figure><p><strong>3. @ViewBuilder and Conditional Rendering Optimization<br></strong>A major advantage of @ViewBuilder is its ability to <strong>conditionally exclude</strong> views from the hierarchy.</p><p><strong>Example Without @ViewBuilder (Inefficient) ❌<br></strong>• <strong>Issue:</strong> The else branch still <strong>creates an empty Text view</strong>, which is unnecessary.</p><pre>struct ContentView: View {<br>    var showText = false<br><br>    var body: some View {<br>        VStack {<br>            if showText {<br>                Text(&quot;Visible text&quot;)<br>            } else {<br>                Text(&quot;&quot;)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Example Optimized with @ViewBuilder ✅<br></strong>• <strong>Improvement:</strong> When showText == false, <strong>SwiftUI completely removes the Text view</strong>, improving performance.</p><pre>struct ContentView: View {<br>    var showText = false<br><br>    @ViewBuilder var body: some View {<br>        if showText {<br>            Text(&quot;Visible text&quot;)<br>        }<br>    }<br>}</pre><p><strong>4. @ViewBuilder in Functions to Optimize View Creation</strong></p><p>Instead of using if-else in the body, @ViewBuilder allows <strong>conditionally returning views</strong> inside a function.</p><p><strong>Optimized Conditional View Creation</strong></p><ul><li>When showDetails == false, <strong>SwiftUI does not create detailsView() at all</strong>, saving memory and processing time. ✅</li></ul><pre>struct ContentView: View {<br>    var showDetails = false<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Main Content&quot;)<br>            detailsView()<br>        }<br>    }<br><br>    @ViewBuilder<br>    func detailsView() -&gt; some View {<br>        if showDetails {<br>            Text(&quot;Additional Details&quot;)<br>        }<br>    }<br>}</pre><p><strong>5. @ViewBuilder and Lazy Evaluation</strong></p><p>SwiftUI <strong>only evaluates views when necessary</strong>, reducing <strong>CPU and memory consumption</strong>.</p><p><strong>Example: Using @ViewBuilder in a Lazy List</strong></p><pre>struct LazyListView: View {<br>    var body: some View {<br>        List(1...1000, id: \.self) { index in<br>            rowView(index: index)<br>        }<br>    }<br><br>    @ViewBuilder<br>    func rowView(index: Int) -&gt; some View {<br>        if index % 2 == 0 {<br>            Text(&quot;Row \(index)&quot;)<br>        }<br>    }<br>}</pre><p>📌 <strong>Performance Gain:<br></strong>• The rowView(index:) function is <strong>only evaluated when required</strong>, avoiding unnecessary computations.</p><p><strong>6. When to Use @ViewBuilder</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcGf5IKfCg2Tg7NhR9HQZA.png" /></figure><h3>What is the difference between stateful and stateless views in SwiftUI?</h3><p>In SwiftUI, views can be categorized as <strong>stateful</strong> or <strong>stateless</strong> based on their management and ownership of data:</p><p><strong>Stateful Views: </strong>These views own and manage their internal state, utilizing property wrappers like <a href="http://twitter.com/State">@State</a> or <a href="http://twitter.com/StateObject">@StateObject</a> to handle data that can change over time.</p><p><strong>Characteristics:</strong></p><ul><li><strong>Internal State Management</strong>: Stateful views maintain their own state, allowing them to update independently when their data changes.</li><li><strong>Direct User Interaction:</strong> They often handle user inputs directly, modifying their state in response to events.</li></ul><pre>struct CounterView: View {<br>    @State private var count = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(count)&quot;)<br>            Button(&quot;Increment&quot;) {<br>                count += 1<br>            }<br>        }<br>    }<br>}</pre><p><strong>Stateless Views: </strong>These views do not own any state. Instead, they rely entirely on external data passed to them, typically through initializer parameters or bindings.</p><p><strong>Characteristics:</strong></p><ul><li><strong>Purely Presentational:</strong> Stateless views focus solely on rendering UI based on the provided data without managing or mutating it.</li><li><strong>Enhanced Reusability:</strong> By not holding state, these views are more reusable and easier to test, as they don’t depend on internal data.</li></ul><pre>struct LabelView: View {<br>    let text: String<br><br>    var body: some View {<br>        Text(text)<br>    }<br>}</pre><p><strong>Connect with Me on LinkedIn!</strong></p><p>If you found this guide helpful, feel free to connect with me on LinkedIn! Let’s grow, learn, and collaborate together.</p><blockquote><em>🔗 </em><a href="https://www.linkedin.com/in/ahilendran/"><em>Follow me on LinkedIn</em></a></blockquote><p>Your feedback and thoughts are always welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20d2517f1e32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Testing in iOS with XCTest]]></title>
            <link>https://medium.com/@eahilendran/performance-testing-in-ios-with-xctest-9bb070669543?source=rss-8d8df9c5eb5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb070669543</guid>
            <dc:creator><![CDATA[Ahil NS]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 21:24:26 GMT</pubDate>
            <atom:updated>2025-02-15T01:09:11.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_v6Skd9mfQlqcpbzECpxw.png" /></figure><h3><strong>Introduction</strong></h3><p>Performance testing is essential for ensuring that an iOS application runs smoothly, efficiently uses system resources, and provides a seamless user experience. Apple provides powerful tools such as `XCTest`, `Xcode Instruments`, and `os_signpost` for measuring application performance.</p><p>In this article, we’ll explore how to write performance test cases using `XCTest`, measure key performance metrics, and integrate tests into a sample project. We will also walk through common performance issues and how to detect and fix them using XCTest metrics.</p><h3><strong>Measurement Metrics in XCTest</strong></h3><p>XCTest provides several built-in performance metrics that allow developers to measure different aspects of app performance. Below is an overview of the available metrics and how they help in performance testing.</p><p><strong>1. XCTMetric (Protocol)</strong><br>`XCTMetric` is a protocol that defines the methods required for gathering performance metrics in XCTest. All the following metric classes conform to this protocol and are used in `measure(metrics:)` to record performance data.</p><p><strong>2. XCTCPUMetric (CPU Usage Monitoring)</strong><br>`XCTCPUMetric` measures CPU activity during a performance test. This metric is useful for detecting high CPU usage, which can lead to excessive battery drain and sluggish app performance.</p><p><strong>Use case:</strong><br>- Detecting CPU spikes during intensive tasks such as image processing, JSON parsing, or database queries.</p><pre>measure(metrics: [XCTCPUMetric()]) {<br>    myApp.runHeavyComputation()<br>}</pre><p><strong>3. XCTClockMetric (Elapsed Time Measurement)</strong><br>`XCTClockMetric` records the total time elapsed during a performance test. This is useful for tracking how long a specific operation takes to execute.</p><p><strong>Use case:</strong><br>- Measuring execution time for API requests, animations, or background tasks.</p><pre>measure(metrics: [XCTClockMetric()]) {<br>    networkManager.fetchData()<br>}</pre><p><strong>4. XCTMemoryMetric (Memory Usage Monitoring)</strong><br>`XCTMemoryMetric` records the physical memory consumed by a test case. It helps in identifying memory leaks and excessive memory consumption.</p><p><strong>Use case:</strong><br>- Detecting memory leaks in view controllers.<br>- Ensuring efficient memory usage in data-intensive tasks.</p><pre>measure(metrics: [XCTMemoryMetric()]) {<br>    myApp.loadLargeImageAssets()<br>}</pre><p><strong>5. XCTOSSignpostMetric (Custom Code Region Monitoring)</strong><br>`XCTOSSignpostMetric` measures the time a specific section of code takes to execute using custom signposts. It is useful for profiling specific application processes.</p><p><strong>Use case:</strong><br>- Measuring performance of critical functions such as database reads/writes or decoding large files.</p><pre>measure(metrics: [XCTOSSignpostMetric(subsystem: &quot;com.myapp&quot;, category: &quot;Rendering&quot;)]) {<br>    myApp.renderGraphics()<br>}</pre><p><strong>6. XCTStorageMetric (Storage Usage Monitoring)</strong><br>`XCTStorageMetric` tracks the amount of data written to storage. This is useful for ensuring that the app does not perform unnecessary disk writes, which can degrade performance over time.</p><p><strong>Use case:</strong><br>- Monitoring the efficiency of caching mechanisms.<br>- Ensuring logs or temporary files do not cause excessive storage writes.</p><pre>measure(metrics: [XCTStorageMetric()]) {<br>    myApp.writeToDatabase()<br>}</pre><p><strong>7. XCTApplicationLaunchMetric (App Launch Time Monitoring)</strong><br>`XCTApplicationLaunchMetric` tracks the duration required for an app to launch. This metric helps developers ensure that app startup time is within the recommended limits.</p><p><strong>Use case:</strong><br>- Ensuring the app launches within Apple’s recommended **400ms for cold starts and 200ms for warm starts**.</p><pre>measure(metrics: [XCTApplicationLaunchMetric()]) {<br>    XCUIApplication().launch()<br>}</pre><h3><strong>Step 1: App Launch Performance Testing (XCTApplicationLaunchMetric)</strong></h3><h4>Common Issues That Cause Slow App Launch</h4><p>Several factors can cause slow app launch times. Below are some common reasons:</p><ol><li><strong>Heavy computations in </strong><strong>init()</strong> (e.g., performing expensive calculations before the app is interactive).</li><li><strong>Blocking network calls on launch</strong> (e.g., fetching data synchronously from an API before showing the UI).</li><li><strong>Loading large assets in memory</strong> (e.g., preloading images, videos, or large JSON files into memory before rendering the UI).</li><li><strong>Excessive database queries</strong> (e.g., querying large amounts of data from Core Data or SQLite on startup).</li><li><strong>Too many UI elements being rendered initially</strong> (e.g., loading a complex UI hierarchy with thousands of views immediately).</li><li><strong>High memory footprint during launch</strong> (e.g., creating too many objects and consuming RAM excessively).</li><li><strong>Slow file I/O operations</strong> (e.g., reading large files from disk synchronously on the main thread).</li><li><strong>Excessive logging during startup</strong> (e.g., printing too many debug statements in production builds).</li></ol><h4>Example: Fixing Slow Launch Due to Heavy Computation in init()</h4><p>In this section, we will focus on <strong>Issue #1: Heavy computations in </strong><strong>init()</strong> and demonstrate how to fix it.</p><p>When an iOS app starts, it should initialize quickly and become interactive within <strong>400ms for a cold start</strong> and <strong>200ms for a warm start</strong> (as per Apple’s recommendations). However, if too many computations are executed in the init() method, they block the main thread, causing slow launch times.</p><h4>Problematic Code with Performance Issue</h4><pre>import SwiftUI<br>@main<br>struct PerformanceTestingApp: App {<br>    init() {<br>        loadHeavyData()<br>    }<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>    <br>    func loadHeavyData() {<br>        for _ in 0..&lt;1_000_000 {<br>            _ = UUID().uuidString<br>        }<br>        print(&quot;Heavy Data Loaded&quot;)<br>    }<br>}</pre><p><strong>Why is this code slow?</strong></p><ul><li>The loadHeavyData() function is executed <strong>synchronously on the main thread</strong> during app launch.</li><li>It generates <strong>1,000,000 UUIDs</strong>, consuming CPU resources <strong>before</strong> the UI even appears.</li><li>This delays app launch and results in a poor user experience.</li></ul><p><strong>How to Fix It?</strong></p><p>Instead of performing <strong>heavy work synchronously in </strong><strong>init()</strong>, we should <strong>offload</strong> it to a <strong>background thread</strong> using Swift&#39;s Task(priority: .background).</p><h4>Optimized Code (Faster App Launch)</h4><pre>import SwiftUI<br><br>@main<br>struct PerformanceTestingApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}<br><br>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;Hello, SwiftUI!&quot;)<br>            .task {<br>                await loadHeavyData()<br>            }<br>    }<br>    <br>    private func loadHeavyData() async {<br>        // Simulate heavy data loading<br>        for _ in 0..&lt;1_000_000 {<br>            _ = UUID().uuidString<br>        }<br>    }<br>}</pre><h4>Performance Testing Code</h4><p>To ensure the app <strong>always meets performance expectations</strong>, we can write a <strong>performance test using </strong><strong>XCTApplicationLaunchMetric</strong>.</p><pre>import XCTest<br>class PerformanceTests: XCTestCase {<br>    @MainActor<br>    func testLaunchPerformance() throws {<br>        let measureOptions = XCTMeasureOptions()<br>        measureOptions.iterationCount = 10<br>    <br>        measure(metrics: [XCTApplicationLaunchMetric()], options: measureOptions) {<br>            XCUIApplication().launch()<br>        }<br>    }<br>}</pre><h4>What does this test do?</h4><ul><li>✅ <strong>Measures how long it takes to launch the app</strong> using XCTApplicationLaunchMetric().</li><li>✅ <strong>Runs the test 10 times (</strong><strong>iterationCount = 10)</strong> to get an <strong>accurate average</strong>.</li><li>✅ <strong>Fails if launch time is consistently higher than the baseline</strong>.</li></ul><h3>How to Set a Baseline for Performance Tests</h3><p>Setting a <strong>baseline</strong> ensures that performance tests fail only when there’s a significant regression.</p><h3>Steps to Set a Baseline in Xcode</h3><ol><li><strong>Run the test once manually</strong>:</li></ol><ul><li>Open Xcode.</li><li>Run <strong>⌘ + U</strong> to execute testLaunchPerformance().</li></ul><p><strong>2. Open the Test Navigator</strong>:</p><ul><li>Go to <strong>Test Navigator (</strong><strong>⌘ + 6)</strong>.</li><li>Select testLaunchPerformance.</li></ul><p><strong>3. Find the Performance Metrics</strong>:</p><ul><li>Click on testLaunchPerformance.</li><li>The <strong>measured launch duration</strong> (e.g., <strong>1.89s</strong>) will be displayed.</li></ul><p><strong>4. Set a Baseline</strong>:</p><ul><li>Click <strong>Set Baseline</strong> next to the recorded duration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*BULSVUGXMvPeDsdaC16JjA.png" /></figure><p><strong>5. Re-run the test</strong> (⌘ + U):</p><ul><li>Now, the test will <strong>fail if the app takes longer than the baseline</strong>.</li></ul><h3>Test Failure When App Launch Time Exceeds the Baseline</h3><p>If the launch time <strong>exceeds the baseline</strong>, the test will <strong>fail</strong>:</p><h4>Setting 1.89s as Baseline</h4><ul><li>The baseline is set to <strong>1.89s</strong>.</li><li>If future runs exceed <strong>1.89s</strong>, the test will <strong>fail</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdj5CdRw0ghOviPjvddRVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*-egA4DEKiQp6rh5JBNf5CQ.png" /></figure><p>Like <strong>App Launch Performance</strong>, we can track the same for <strong>CPU Usage, Memory Usage, Smooth Scrolling</strong>, and more.</p><h3>Conclusion</h3><p>By implementing <strong>XCTest performance testing</strong>, you can ensure:</p><ul><li>🚀 <strong>Fast app launches</strong></li><li>💾 <strong>Efficient memory usage</strong></li><li>🔥 <strong>Optimized CPU performance</strong></li><li>📜 <strong>Smooth scrolling</strong></li></ul><p>Using XCTApplicationLaunchMetric, XCTCPUMetric, XCTMemoryMetric, and XCTOSSignpostMetric, you can <strong>detect regressions early</strong>, optimize your app, and improve the user experience. Integrating these tests into your CI/CD pipeline ensures <strong>continuous monitoring</strong> and helps maintain high performance standards.</p><p>Happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb070669543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Swift Testing]]></title>
            <link>https://medium.com/@eahilendran/comprehensive-guide-to-swift-testing-afee425e159b?source=rss-8d8df9c5eb5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/afee425e159b</guid>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[parameterized-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[xctest-migration]]></category>
            <dc:creator><![CDATA[Ahil NS]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 18:40:29 GMT</pubDate>
            <atom:updated>2025-01-24T18:40:29.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpBnfVQA6cmFhPBnAMOtCg.png" /></figure><p>Quality and reliability are crucial for delivering a great user experience. Automated testing is a proven way to achieve and maintain software quality over time. <strong>Testing is a crucial step in the development process.</strong> It helps surface issues before your code reaches your users and gives you confidence that you’re shipping a quality product.</p><p>Swift Testing introduces a new open-source package for testing your code using Swift. Designed specifically for the Swift language, it leverages modern features like concurrency and macros. <strong>It is included with Xcode 16</strong> and supports all major platforms, including Linux and Windows.</p><p>This guide provides a step-by-step walkthrough, leveraging examples from both XCTest and Swift Testing, and highlights key features to ease migration. By adopting Swift Testing, you gain:</p><ul><li><strong>Descriptive, Organized Tests</strong>: Enhances test clarity and maintainability.</li><li><strong>Actionable Failures</strong>: Offers detailed diagnostics for failed tests, simplifying debugging.</li><li><strong>Scalability</strong>: Facilitates parameterized testing and parallel execution for larger projects.</li></ul><blockquote><strong><em>Requirements: </em></strong><em>Xcode 16+ &amp; Swift 6+</em></blockquote><h3>Why Migrate to Swift Testing?</h3><p>Swift Testing offers several advantages:</p><ul><li><strong>Improved Readability:</strong> Concise syntax improves code clarity.</li><li><strong>Type Safety:</strong> Reduces runtime errors by catching issues at compile time.</li><li><strong>Flexibility:</strong> Supports parameterized testing, traits, and parallel execution.</li><li><strong>Enhanced Debugging:</strong> Detailed results for each test case make debugging easier.</li></ul><p>Let’s dive deeper into Swift Testing by comparing it with XCTest and exploring practical use cases.</p><h3><strong>Swift Testing vs XCTest</strong></h3><p>When transitioning to <strong>Swift Testing</strong>, understanding how it compares with <strong>XCTest</strong> is crucial. While both frameworks aim to test code functionality, <strong>Swift Testing</strong> introduces modern features that enhance readability, maintainability, and efficiency. Below, we break down the differences and similarities between these two testing frameworks.</p><p><strong>Test Functions</strong></p><p>In XCTest, a test is defined by naming methods with the prefix test. Swift Testing, however, uses the @Test attribute to explicitly denote test functions, allowing for better clarity and organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJMg9rfKExnBZ7-6uSGm9Q.png" /><figcaption><strong>Swift Testing vs XCTest Test Functions</strong></figcaption></figure><p><strong>Expectations and Assertions</strong></p><p>Expectations (called assertions in XCTest) are used to validate conditions within tests. Swift Testing simplifies this process with just two macros, #expect and #require, replacing XCTest’s numerous XCTAssert functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9UJJewKtux2f2nc4FrNSg.png" /><figcaption><strong>Swift Testing vs XCTest Expectations and Assertions</strong></figcaption></figure><p><strong>Test Suites</strong></p><p>Test suites are collections of related tests, offering better organization. While XCTest only supports class types for suites, Swift Testing allows for <strong>structs</strong>, <strong>actors</strong>, and <strong>classes</strong>. Structs are encouraged to maintain value semantics, minimizing state-sharing issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gd4KUkvyfJhW2_EygfjF2w.png" /><figcaption><strong>Swift Testing vs XCTest-Test Suites</strong></figcaption></figure><p><strong>Key Advantages of Swift Testing</strong></p><p>1. <strong>Unified Expectations:</strong></p><ul><li>Instead of memorizing various XCTAssert functions, developers can use intuitive language operators within #expect and #require.</li></ul><p>2. <strong>Concurrency Support:</strong></p><ul><li>Swift Testing leverages <strong>Swift Concurrency</strong>, enabling parallel execution of tests even on physical devices like iPhones and Apple Watches.</li></ul><p>3. <strong>Value Semantics:</strong></p><ul><li>By supporting structs for suites, Swift Testing prevents unintentional state sharing, ensuring safer and cleaner test logic.</li></ul><p>4. <strong>Traits for Test Metadata:</strong></p><ul><li>Swift Testing allows developers to attach traits to tests or suites, offering better runtime control, filtering, and organization.</li></ul><p>5. <strong>Improved Debugging:</strong></p><ul><li>Parameterized tests and individual argument-level reruns simplify debugging and make it easier to identify and isolate issues.</li></ul><h3><strong>Migrating from XCTest to Swift Testing</strong></h3><p>Migrating your test suite from XCTest to Swift Testing can be done incrementally, allowing both frameworks to coexist in the same target. This flexibility ensures a smooth transition without disrupting your development workflow. Below are the key points and recommended practices for migration.</p><p><strong>Recommended Practices</strong></p><p>1. <strong>Coexistence</strong>: Swift Testing and XCTest tests can share a single unit test target. You don’t need to create a separate target for Swift Testing tests.</p><p>2. <strong>Consolidation of Similar Tests</strong>: Consolidate multiple similar XCTest methods into one parameterized test using Swift Testing. This simplifies test management and enhances readability.</p><p>3. <strong>Migrate Single-Method Classes</strong>: If an XCTest class contains only one test method, consider migrating it to a global @Test function in Swift Testing.</p><p>4. <strong>Simplify Test Names</strong>: Unlike XCTest, where the prefix “test” is required for discovery, Swift Testing uses the @Test attribute. This eliminates the need for redundant “test” prefixes in method names.</p><blockquote><strong><em>Tip:</em></strong><em> Avoid using </em><em>XCTAssert(...) or </em><em>#expect(...) across Swift Testing and XCTest to maintain clear boundaries between the two frameworks.</em></blockquote><h3><strong>When use XCTest ⚠️?</strong></h3><p>There are scenarios where XCTest should still be used:</p><ul><li><strong>UI Automation</strong>: Tests relying on XCUIApplication for user interface automation must remain in XCTest.</li><li><strong>Performance Testing</strong>: Tests using performance APIs like XCTMetric are not yet supported in Swift Testing.</li><li><strong>Objective-C Requirements</strong>: Tests that need to be written in Objective-C are only possible with XCTest.</li></ul><h3>Writing Test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXUOuBywhDyHDcxey9jTTw.png" /><figcaption>Add Unit Testing Target</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crm4z0iSFQQLdum09umN_w.png" /><figcaption>Swift Testing System</figcaption></figure><p>Lets write our first Test</p><pre>struct SwiftTestingExampleTests {<br>    <br>    let calculator = Calculator()<br>    <br>    @Test func additionTest() {<br>        let result = calculator.add(2, 2)<br>        #expect(result == 4, &quot;Addition failed: Expected 4, got \(result)&quot;)<br>    }<br>    <br>}<br><br>struct Calculator {<br>    func add(_ a: Int, _ b: Int) -&gt; Int {<br>        return a + b<br>    }<br>}</pre><h3>Building Blocks of Swift Testing</h3><p>1. <strong>Test Functions</strong>: Functions annotated with @Test allow you to explicitly define test cases, supporting instance, static, and global methods.</p><p>2. <strong>Expectations</strong>: Using #expect and #require, Swift Testing simplifies validation. These macros support concise expressions with detailed failure diagnostics, eliminating the need for a variety of specialized assertion methods.</p><p>3. <strong>Traits</strong>: Traits like tags and time limits offer a flexible way to customize test behavior, group related tests, and provide additional metadata for easier organization and reporting.</p><p>4. <strong>Suites</strong>: The @Suite attribute groups related tests and suites into hierarchical structures. This supports test organization, shared setup/teardown logic, and nested grouping.</p><p>Let’s Learn About All Building Blocks of Swift Testing in Depth</p><h3><strong>Understanding @Test in Swift Testing</strong></h3><p>In Swift Testing, the @Test attribute plays a crucial role in defining and organizing test cases. It replaces the traditional prefix-based approach (e.g., func testExample()) used in XCTest, making test functions more expressive and versatile.</p><p><strong>Key Features of @Test</strong></p><p>1. <strong>Annotation-Based Test Discovery</strong></p><ul><li>Test functions are explicitly marked using the @Test attribute.</li><li>No need to name test functions with a test prefix; the annotation itself indicates a test.</li></ul><pre>@Test func exampleTest() {<br>    #expect(value == expectedValue)<br>}</pre><p>2. <strong>Supports Multiple Function Types</strong></p><ul><li>Test functions can be global or encapsulated within a type.</li><li>This flexibility allows better modularity and organization.</li></ul><p><strong>Example 1: Encapsulated Tests</strong></p><pre>struct MathTests {<br>    @Test func multiplicationTest() {<br>        let product = 3 * 3<br>        #expect(product == 9)  // Ensures the multiplication logic is correct<br>    }<br>}</pre><p><strong>Example 2: Global Tests</strong></p><pre>@Test func subtractionTest() {<br>    let difference = 10 - 4<br>    #expect(difference == 6)  // Verifies subtraction<br>}</pre><p>3. <strong>Asynchronous and Error-Handling Support</strong></p><p>Test functions can be marked as async and throws, simplifying testing for asynchronous operations and error scenarios.</p><p>Example:</p><pre>// Asynchronous test case for fetching data<br> @Test func fetchDataTest() async throws {<br>     let mockData = try await fetchMockData()<br>     #expect(mockData.isValid)  // Validate that fetched data meets criteria<br> }<br><br>// Mock function for fetching data (simulating an async operation)<br>func fetchMockData() async throws -&gt; MockData {<br>    return MockData(isValid: true)<br>}<br><br>// Mock data structure<br>struct MockData {<br>    let isValid: Bool<br>}</pre><p><strong>4. Global Actor Isolation</strong></p><ul><li>Tests can be isolated to specific global actors (e.g., @MainActor) to ensure thread safety. This is especially useful for testing UI components or other thread-sensitive code.</li></ul><p>Example:</p><pre>@Test @MainActor func uiButtonStateTest() {<br>    let button = createButton()<br>    button.isEnabled = true<br>    #expect(button.isEnabled)    // Verify the button is enabled<br>}</pre><h3><strong>Understanding #expect in Swift Testing</strong></h3><p>The #expect macro in Swift Testing provides a flexible and expressive way to validate expected conditions. Its concise syntax enhances readability while its detailed failure reports help developers debug effectively.</p><p>The #expect macro is really flexible. You can pass any expression, including operators or method calls, and it will show you detailed results if it fails. This makes it an essential tool for both simple and complex test cases.</p><p><strong>Key Features:</strong></p><ul><li><strong>Validation</strong>: Validates expected conditions using ordinary expressions.</li><li><strong>Error Reporting</strong>: Captures the source code and subexpression values when a condition fails.</li><li><strong>Flexibility</strong>: Works seamlessly with a variety of expressions and operators.</li></ul><p><strong>Examples:</strong></p><p>Here’s a practical implementation of the #expect macro in a test suite, including both passing and failing scenarios to demonstrate detailed failure diagnostics.</p><pre>import Testing<br><br>struct ExampleTests {<br>    <br>    @Test<br>    func testBasicExpectations() {<br>        // Validating simple conditions<br>        #expect(1 + 1 == 2) // This will pass<br>        <br>        let userName = &quot;Alice&quot;<br>        #expect(userName == &quot;Alice&quot;) // This will pass<br>        <br>        let numbers = [1, 2, 3]<br>        #expect(numbers.contains(2)) // This will pass<br>        <br>        let emptyArray: [Int] = []<br>        #expect(emptyArray.isEmpty) // This will pass<br>    }<br>    <br>    @Test<br>    func testFailingExpectations() {<br>        // A condition that will fail<br>        #expect(1 + 1 == 3) // This will fail<br>        <br>        let user = (name: &quot;Bob&quot;, age: 25)<br>        #expect(user.name == &quot;Alice&quot;) // This will fail<br>        <br>        let nonEmptyArray = [5, 6, 7]<br>        #expect(nonEmptyArray.isEmpty) // This will fail<br>        <br>        let numbers = [8, 9, 10]<br>        #expect(numbers.contains(2)) // This will fail<br>    }<br>}</pre><p>We can see the detailed logs to understand the error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQbfL6kuKEhq4oBXvSia9w.png" /></figure><h3>Assertions and Expectations</h3><p>In Swift Testing, traditional XCTest assertions have been replaced with expressive and type-safe syntax. This modern approach makes it easier to write, read, and debug test cases.</p><p><strong>XCTest vs. Swift Testing: Comparison Table</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*TNUuyEN2Na1oFuA1p_ghCQ.png" /><figcaption>XCTest vs. Swift Testing</figcaption></figure><p><strong>Swift Testing Example:</strong></p><pre>     @Test<br>     func testExpectations() {<br>         #expect(1 + 1 == 2)<br>         #expect(&quot;Hello&quot; != nil)<br>         #expect(10 == 10)<br>         #expect(20 &gt; 10)<br>     }</pre><h3><strong>Required Expectations in Swift Testing</strong></h3><p>Swift Testing introduces <strong>required expectations</strong> to enforce strict conditions in test cases, ensuring that tests halt immediately when a critical condition fails.</p><p>This feature is crucial for scenarios where continuing the test without meeting the required condition would not make sense.</p><p><strong>Key Features:</strong></p><p>1. <strong>Halting Execution</strong>: The #require macro halts test execution immediately upon failure, unlike #expect, which logs the failure and continues.</p><p>2. <strong>Optional Unwrapping</strong>: Safely unwraps optional values, stopping the test if the value is nil.</p><p><strong>Stopping Execution on Failure</strong></p><pre>import Testing<br><br>struct SessionTests {<br>    @Test(&quot;Validate Session is Valid&quot;) func validateSession() throws {<br>        // Example: Create an invalid session<br>        let session = Session(isValid: false)<br>        <br>        // Enforce that the session must be valid<br>        try #require(session.isValid) // Halts here if isValid is false<br>        <br>        // This line will not execute if the above requirement fails<br>        session.invalidate()<br>    }<br>}<br><br>// Define the Session type<br>struct Session {<br>    var isValid: Bool<br><br>    func invalidate() {<br>        print(&quot;Session invalidated&quot;)<br>    }<br>}</pre><p>If session.isValid evaluates to false, the test halts immediately.</p><p><strong>Unwrapping Optionals Safely</strong></p><p>When working with optionals, try #require ensures the test halts if the optional value is nil. This prevents potential runtime errors or invalid checks on nil values.</p><pre>import Testing<br><br>struct PaymentMethodTests {<br>    @Test(&quot;Validate Default Payment Method&quot;) func validateDefaultPaymentMethod() throws {<br>        // Example: Create a list of payment methods<br>        let paymentMethods = [<br>            PaymentMethod(name: &quot;Visa&quot;, isDefault: false),<br>            PaymentMethod(name: &quot;MasterCard&quot;, isDefault: true)<br>        ]<br><br>        // Use #require to unwrap the first payment method<br>        let defaultMethod = try #require(paymentMethods.first(where: { $0.isDefault }))<br>        <br>        // Validate that the default method has the correct properties<br>        #expect(defaultMethod.name == &quot;MasterCard&quot;)<br>        #expect(defaultMethod.isDefault == true)<br>    }<br>    <br>    @Test(&quot;Handle Empty Payment Methods List&quot;) func handleEmptyPaymentMethods() throws {<br>        // Example: Empty list of payment methods<br>        let paymentMethods: [PaymentMethod] = []<br><br>        // Try to require a default payment method (expected to fail)<br>        let defaultMethod = try? #require(paymentMethods.first(where: { $0.isDefault }))<br>        <br>        // Ensure defaultMethod is nil (test succeeds if this condition is met)<br>        #expect(defaultMethod == nil)<br>    }<br>}<br><br>// Define the PaymentMethod type<br>struct PaymentMethod {<br>    let name: String<br>    let isDefault: Bool<br>}</pre><p>This ensures paymentMethods.first is not nil before proceeding, avoiding runtime crashes and providing detailed failure diagnostics.</p><h3><strong>Understanding Traits in Swift Testing</strong></h3><p>Traits in Swift Testing provide a powerful way to enhance and manage test cases. They allow developers to add metadata, control execution conditions, and modify test behavior, making tests more descriptive, flexible, and organized.</p><p><strong>Key Features of Traits:</strong></p><p>1. <strong>Descriptive Metadata</strong>: Traits can include display names, tags, or references to issues, making it easier to understand the purpose of a test at a glance.</p><p>2. <strong>Conditional Execution</strong>: Traits enable tests to run only under specific conditions, such as certain OS versions or server statuses.</p><p>3. <strong>Behavioral Modifications</strong>: Traits can impose time limits, disable tests, or control parallelization within test suites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGBKSUMEleQ3QfxR7QRSkg.png" /></figure><p><strong>Custom Display Name</strong></p><pre>@Test(&quot;Verify User Login&quot;)<br>func userLoginTest() {<br>    let isLoggedIn = loginUser(username: &quot;testUser&quot;, password: &quot;password123&quot;)<br>    #expect(isLoggedIn)<br>}</pre><p>This test is displayed in Xcode with the name <strong>“Verify User Login”</strong>, making it more descriptive.</p><p><strong>Linking to a Bug</strong></p><pre>@Test.bug(&quot;example.com/issues/567&quot;, &quot;Fix API Timeout Issue&quot;)<br>func apiTimeoutTest() {<br>    let response = fetchAPIResponse()<br>    #expect(response.time &lt; 2.0)<br>}</pre><p>The linked bug provides additional context for the test.</p><p><strong>Conditional Execution</strong></p><pre>@Test(.enabled(if: Server.isOnline))<br>func fetchDataWhenOnline() {<br>    let data = fetchDataFromServer()<br>    #expect(!data.isEmpty)<br>}</pre><p>This test will run only if the Server.isOnline condition evaluates to true.</p><p><strong>Setting a Time Limit</strong></p><pre>@Test(.timeLimit(.seconds(5)))<br>func dataProcessingTest() {<br>    let result = processData()<br>    #expect(result.isValid)<br>}</pre><p><strong>Benefits of Traits:</strong></p><ul><li><strong>Improved Organization</strong>: Tests are easier to navigate with descriptive names and tags.</li><li><strong>Execution Control</strong>: Run tests based on dynamic conditions or environment configurations.</li><li><strong>Debugging Made Easy</strong>: Traits like .bug() provide direct links to related issues.</li></ul><h3><strong>Runtime Conditions in Swift Testing</strong></h3><p>Runtime conditions enable dynamic control over test execution based on specific conditions. These conditions allow for flexible and efficient testing by enabling, disabling, or tagging tests based on runtime criteria or platform specifications.</p><p><strong>Common Scenarios for Runtime Conditions</strong></p><ol><li><strong>Specify Conditional Execution</strong></li></ol><ul><li>Use .enabled(if:) to skip a test if a specific condition evaluates to false.</li></ul><pre>@Test(.enabled(if: AppFeatures.isCommentingEnabled))<br>func videoCommenting() {<br>    // Test logic for video commenting feature<br>}</pre><p>2. <strong>Unconditionally Disable Tests</strong></p><ul><li>Use .disabled() with a reason to exclude tests temporarily, including descriptive insights in test results.</li></ul><pre>@Test(.disabled(&quot;Due to a known crash&quot;))<br>func example() {<br>    // Temporarily disabled test logic<br>}</pre><p>3. <strong>Reference Bug Tracking Systems</strong></p><ul><li>Combine .bug() with other traits to link a test to a known issue in a bug tracking system.</li></ul><pre>@Test(.disabled(&quot;Due to a known crash&quot;),<br>      .bug(&quot;example.org/bugs/1234&quot;, &quot;Program crashes at &lt;symbol&gt;&quot;))<br>func example() {<br>    // Test linked to a bug tracker<br>}</pre><p><strong>Control Test Execution by OS Version</strong></p><ul><li>Use @available to restrict tests to specific OS versions.</li></ul><pre>@Test<br>@available(macOS 15, *)<br>func usesNewAPIs() {<br>    // Test logic compatible with macOS 15+<br>}</pre><h3>Parameterized Testing</h3><p>Parameterized testing allows you to run the same test logic with multiple sets of input values. This is particularly useful for reducing duplication and increasing the clarity of your tests.</p><p><strong>Benefits of Parameterized Testing</strong></p><ol><li><strong>Clear Results</strong>: View detailed results for each set of inputs, making it easy to identify failures.</li><li><strong>Debugging Flexibility</strong>: Re-run specific test arguments to debug issues faster.</li></ol><p>3. <strong>Parallel Execution</strong>: Arguments can be executed in parallel, speeding up test runs.</p><p><strong>Use Parameterized Testing ✅</strong></p><pre>import Testing<br><br>struct CalculatorTests {<br>    <br>    let calculator = Calculator()<br>    <br>    // Addition Tests<br>    @Test(arguments: [<br>        (3, 5, 8),<br>        (0, 0, 0),<br>        (-3, -7, -10),<br>        (10, -5, 5)<br>    ])<br>    func testAddition(_ a: Int, _ b: Int, _ expected: Int) {<br>        let result = calculator.add(a, b)<br>        #expect(result == expected, &quot;Addition failed for \(a) + \(b)&quot;)<br>    }<br>}</pre><p><strong>Avoiding Loops in Tests ❌</strong></p><p>While loops can be a common way to repeat similar test logic, they make it harder to isolate specific test failures and debug efficiently. Instead of using loops, Swift Testing’s parameterized testing is a more structured and efficient approach.</p><pre>import Testing<br><br>struct CalculatorLoopTests {<br>    <br>    let calculator = Calculator()<br><br>    @Test func testAdditionWithLoop() {<br>        let testCases = [<br>            (3, 5, 8),<br>            (0, 0, 0),<br>            (-3, -7, -10),<br>            (10, -5, 5)<br>        ]<br><br>        for (a, b, expected) in testCases {<br>            let result = calculator.add(a, b)<br>            #expect(result == expected, &quot;Addition failed for \(a) + \(b): Expected \(expected), got \(result)&quot;)<br>        }<br>    }<br>}</pre><p><strong>Why Parameterized Testing is Better</strong></p><p>1. <strong>Clear Test Results</strong>:</p><ul><li>Each input set is treated as a separate test case.</li><li>The Test Navigator displays results for each input explicitly.</li></ul><p>2. <strong>Independent Execution</strong>:</p><ul><li>Each argument can be re-run independently for debugging.</li><li>Saves time by focusing only on the failed test cases.</li></ul><p>3. <strong>Efficient Parallel Execution:</strong></p><ul><li>Arguments are executed in parallel, reducing overall test runtime.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnV-V5vKPsjlYu-4kAzwRw.png" /><figcaption><strong>Comparison: Loop vs. Parameterized Testing</strong></figcaption></figure><h3>Suites in Swift Testing</h3><p>Suites in Swift Testing allow you to group related test functions or suites, providing better organization and reusable configurations. The grouping is annotated using @Suite. This feature is implicit for types that already contain @Test functions or other suites.</p><p><strong>Key Features of Suites:</strong></p><p>1. <strong>Grouping Related Tests</strong>:</p><ul><li>Organize tests that validate similar features or subsystems.</li><li>Simplifies test management and enhances clarity in the Test Navigator.</li></ul><p>2. <strong>Annotations with </strong>@Suite:</p><ul><li>Use @Suite to explicitly declare a suite for related tests.</li><li>Tags and traits can be applied at the suite level, simplifying test inheritance.</li></ul><p>3. <strong>Stored Properties</strong>:</p><ul><li>Suites can have stored instance properties for managing shared data or configurations.</li></ul><p>4. <strong>Initialization and Cleanup</strong>:</p><ul><li>init and deinit methods are available for setting up and tearing down resources required by the tests.</li></ul><p>5. <strong>Instance Per Test Method</strong>:</p><ul><li>Each @Test method in a suite gets its own instance of the suite.</li></ul><p><strong>Grouping Tests with Suites</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgl0678Bv1w-Lt5sIhTyQQ.png" /></figure><h3>Test Tags and Traits</h3><p>Tags and traits allow grouping and filtering tests for execution or reporting.</p><h4>Recommended Practices:</h4><ul><li>Use tags over test names for flexibility.</li><li>Prefer .enabled traits for conditional inclusion.</li></ul><pre>@Suite(.tags(.formatting)) struct MetadataPresentation {<br>    @Test func formattedDuration() async throws {<br>        let video = try await videoLibrary.video(named: &quot;By the Lake&quot;)<br>        #expect(video.formattedDuration == &quot;01m 19s&quot;)<br>    }<br>}</pre><p>Tags can also be shared across tests for improved management and filtering.</p><h3>Runtime Conditions</h3><p>Swift Testing supports conditional execution of tests based on OS availability, replacing runtime checks for better clarity.</p><pre>@Test<br>@available(macOS 15, *)<br>func usesNewAPIs() {<br>    // Test logic for macOS 15+<br>}</pre><p>This ensures tests run only on supported versions without requiring additional runtime checks.</p><h3>Disabling Tests</h3><p>Temporarily disable tests with a descriptive reason or link them to a bug tracking system.</p><pre>@Test(.disabled(&quot;Known crash&quot;), .bug(&quot;example.org/bugs/1234&quot;, &quot;Crashes at &lt;symbol&gt;&quot;))<br>func example() {<br>    // Test logic<br>}</pre><p>Including a reason in the .disabled trait provides better insights in test reports.</p><p><strong>Connect with Me on LinkedIn!</strong></p><p>If you found this guide helpful, feel free to connect with me on LinkedIn! Let’s grow, learn, and collaborate together.</p><blockquote>🔗 <a href="https://www.linkedin.com/in/ahilendran/">Follow me on LinkedIn</a></blockquote><p>Your feedback and thoughts are always welcome!</p><p>References</p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2024/10195/">Go further with Swift Testing</a> — WWDC24 Sessions</li><li><a href="https://developer.apple.com/documentation/testing">Swift Testing Apple Documentation</a></li><li><a href="https://developer.apple.com/documentation/testing/migratingfromxctest">https://developer.apple.com/documentation/testing/migratingfromxctest</a></li><li><a href="https://github.com/swiftlang/swift-testing">https://github.com/swiftlang/swift-testing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afee425e159b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>