<?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 Sachindra Fernando on Medium]]></title>
        <description><![CDATA[Stories by Sachindra Fernando on Medium]]></description>
        <link>https://medium.com/@sachindrafernando3?source=rss-f7169ed3b1dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*McK7dIFlYvyHqjU5ESoBGw.jpeg</url>
            <title>Stories by Sachindra Fernando on Medium</title>
            <link>https://medium.com/@sachindrafernando3?source=rss-f7169ed3b1dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:59:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachindrafernando3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift 6.4 at WWDC26: Every Important Update Explained with Examples]]></title>
            <link>https://medium.com/@sachindrafernando3/swift-6-4-at-wwdc26-every-important-update-explained-with-examples-df42f1ec84c1?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/df42f1ec84c1</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[every-years]]></category>
            <category><![CDATA[wwdc26]]></category>
            <category><![CDATA[swift-6-4]]></category>
            <category><![CDATA[swift-6]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 22:01:30 GMT</pubDate>
            <atom:updated>2026-07-02T22:01:30.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bv_xY9Xp5By25ibqk867JQ.png" /></figure><p>Swift continues to evolve every year, but not every release completely changes how you write apps.</p><p>Swift 6.4, announced at WWDC26, is a <strong>quality-of-life release</strong>. Instead of introducing a new paradigm, it focuses on something more practical:</p><blockquote><em>making Swift easier to write, safer to use, and clearer when things go wrong.</em></blockquote><p>If you’re an iOS developer, especially early in your journey, this release is less about “learning new Swift” and more about:</p><ul><li>writing less repetitive code</li><li>understanding errors faster</li><li>working more safely with concurrency</li><li>improving performance under the hood</li></ul><p>Let’s go through the most important updates with simple examples.</p><h3>1. Simpler Availability Checks Across Apple Platforms</h3><p>If you’ve ever written code for multiple Apple platforms, you know how repetitive availability checks can get.</p><h3>❌ Before Swift 6.4</h3><pre>@available(iOS 27, *)<br>@available(macOS 27, *)<br>@available(tvOS 27, *)<br>@available(watchOS 27, *)<br>func newFeature() {}</pre><p>This works, but it’s verbose and easy to miss a platform.</p><h3>✅ After Swift 6.4</h3><p>Swift introduces a simplified form:</p><pre>@available(anyAppleOS 27, *)<br>func newFeature() {}</pre><h3>💡 Why this matters</h3><p>Instead of repeating the same version for every platform, you now express your intent once.</p><p>For beginners, this means:</p><ul><li>less boilerplate</li><li>fewer mistakes</li><li>easier cross-platform development</li></ul><h3>2. Concurrency Improvements (Safer + Easier to Debug)</h3><p>Swift concurrency (async/await, actors, Sendable) is powerful — but often confusing for beginners.</p><p>Swift 6.4 does <strong>not change the model</strong>, but it improves how the compiler guides you.</p><h3>🧠 Better concurrency diagnostics</h3><p>When you accidentally pass unsafe data across concurrency boundaries, Swift now explains the problem more clearly.</p><h3>❌ Before</h3><p>You might see confusing messages like:</p><ul><li>“non-sendable type used in concurrent context”</li></ul><h3>✅ After Swift 6.4</h3><p>Errors are more specific:</p><ul><li>what type caused the issue</li><li>where isolation was violated</li><li>why Swift considers it unsafe</li></ul><h3>📦 What about Sendable?</h3><p>Sendable is still a core part of Swift concurrency.</p><p>But in Swift 6.4, the improvement is:</p><blockquote><em>The compiler gives clearer feedback when something is not Sendable.</em></blockquote><h3>Simple idea:</h3><p>If you pass data between concurrent tasks, Swift checks:</p><blockquote><em>“Is this safe to share?”</em></blockquote><p>If not, it now explains <em>why</em> more clearly.</p><h3>Beginner takeaway</h3><p>You still need to understand concurrency rules, but Swift helps you fix mistakes faster instead of just rejecting your code.</p><h3>3. Async Code in defer Blocks</h3><p>Before Swift 6.4, defer could not run async code.</p><h3>❌ Before</h3><pre>defer {<br>    // could NOT use await here<br>}</pre><p>Developers had to use workarounds like Task.</p><h3>✅ After Swift 6.4</h3><p>You can now safely write:</p><pre>defer {<br>    await cleanup()<br>}</pre><h3>💡 Why this matters</h3><p>This is especially useful for:</p><ul><li>releasing resources</li><li>closing network connections</li><li>cleanup logic that needs async work</li></ul><p>It makes cleanup code more natural and readable.</p><h3>4. Swift Testing Improvements</h3><p>Swift Testing continues to evolve as a modern alternative to XCTest.</p><h3>What’s improved</h3><ul><li>smoother interoperability with XCTest</li><li>cleaner test syntax</li><li>more readable assertions</li></ul><h3>Example</h3><pre>import Testing<br><br>@Test<br>func addingNumbersWorks() {<br>    #expect(2 + 2 == 4)<br>}</pre><h3>Why this matters</h3><p>For beginners:</p><ul><li>tests feel like normal Swift code</li><li>less boilerplate than XCTest</li><li>easier to read and maintain</li></ul><h3>5. Better Compiler Diagnostics</h3><p>One of the most underrated improvements in Swift 6.4 is:</p><blockquote><em>clearer compiler errors</em></blockquote><h3>What changed</h3><p>When something goes wrong, Swift now:</p><ul><li>explains the issue more clearly</li><li>points to the exact cause more precisely</li><li>suggests better fixes</li></ul><h3>Beginner impact</h3><p>This reduces one of the biggest frustrations in learning Swift:</p><blockquote><em>confusing compiler errors that are hard to decode.</em></blockquote><h3>6. Foundation Performance Improvements</h3><p>Swift 6.4 includes performance improvements in core Apple frameworks.</p><p>One example highlighted by Apple:</p><ul><li>faster URL parsing (up to 4× in some cases)</li></ul><h3>Why this matters</h3><p>Even if your code doesn’t change:</p><ul><li>apps feel faster</li><li>system APIs are more efficient</li><li>less hidden overhead in common operations</li></ul><h3>7. What DIDN’T Change (Important)</h3><p>To avoid confusion, Swift 6.4 does NOT:</p><ul><li>change the concurrency model</li><li>remove actors or Sendable</li><li>introduce a new async system</li><li>break SwiftUI fundamentals</li></ul><p>Instead, it focuses on:</p><blockquote><em>improving clarity, safety, and developer experience</em></blockquote><h3>8. Should You Upgrade?</h3><h3>👍 Yes, if:</h3><ul><li>you want better compiler messages</li><li>you use concurrency</li><li>you build for multiple Apple platforms</li><li>you want cleaner Swift code</li></ul><h3>🤷 Not urgent if:</h3><ul><li>your app is stable</li><li>you’re not targeting the latest SDK features yet</li></ul><p>This is a <strong>quality-of-life upgrade</strong>, not a forced migration.</p><h3>9. Real WWDC26 &amp; Apple Documentation References</h3><p>All features mentioned in this article are based on official WWDC26 Swift materials:</p><h3>📌 Apple Official Swift Guide (WWDC26)</h3><ul><li>Swift 6.4 overview</li><li>anyAppleOS availability simplification</li><li>async support in defer</li><li>improved concurrency diagnostics</li><li>Swift Testing improvements</li><li>Foundation performance updates</li></ul><h3>📌 WWDC26 Swift Session Highlights</h3><p>Key session coverage includes:</p><ul><li>availability improvements (anyAppleOS)</li><li>async/await in defer</li><li>Sendable-related concurrency diagnostics improvements</li><li>iteration improvements for non-copyable types</li><li>Foundation performance improvements</li></ul><h3>📌 Swift Evolution &amp; Platform Design Notes</h3><p>Additional technical details and rationale:</p><ul><li>why anyAppleOS was introduced</li><li>concurrency safety improvements and diagnostics focus</li><li>gradual evolution of Swift concurrency safety model</li></ul><h3>Final Thoughts</h3><p>Swift 6.4 is not a dramatic rewrite of the language.</p><p>Instead, it quietly improves the everyday experience of writing Swift:</p><ul><li>less repetitive code</li><li>clearer compiler feedback</li><li>safer concurrency debugging</li><li>better performance in core APIs</li></ul><p>If Swift used to feel like it sometimes “got in your way,” this release is about removing that friction.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df42f1ec84c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Professional Testing in Swift]]></title>
            <link>https://medium.com/@sachindrafernando3/professional-testing-in-swift-d2efdade68df?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2efdade68df</guid>
            <category><![CDATA[uitest]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift-testing]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 19:57:43 GMT</pubDate>
            <atom:updated>2026-06-27T21:35:49.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhO464x5xsjOKmYPHfjUwg.png" /></figure><p><strong>This is the final article in a 3-part Swift testing series.</strong></p><ul><li><a href="https://medium.com/@sachindrafernando3/modern-testing-in-swift-from-zero-to-confident-f9dfe584dfdc?sharedUserId=sachindrafernando3">Part 1: Modern Testing in Swift: From Zero to Confident</a></li><li><a href="https://medium.com/@sachindrafernando3/building-testable-swift-applications-0a4e3fd2fd79?sharedUserId=sachindrafernando3">Part 2: Building Testable Swift Applications</a></li><li>✅ Part 3: Professional Testing in Swift <em>(you’re here)</em></li></ul><p>If you haven’t read the previous articles, I recommend starting from Part 1, where we build the fundamentals before moving into architecture and production testing.</p><h3>UI Testing, Performance, Code Coverage, CI/CD, and Building a Long-Term Testing Strategy</h3><blockquote>The goal of testing isn’t to have the most tests. It’s to have the right tests.</blockquote><p>If you’ve followed this series from the beginning, you’ve already learned two important lessons.</p><p>First, testing is about confidence, not code coverage.</p><p>Second, testable software starts with good design.</p><p>Now it’s time for the final step.</p><p>How do professional teams test applications that contain hundreds of screens, thousands of files, and millions of users?</p><p>The answer isn’t “write more tests.”</p><p>It’s having a strategy.</p><p>In this final article, we’ll move beyond unit testing and explore the tools and practices that help teams maintain confidence as their applications continue to grow.</p><h3>Testing Is an Investment</h3><p>One of the biggest misconceptions about testing is that it’s a one-time task.</p><p>It isn’t.</p><p>Testing is part of the software lifecycle.</p><p>Every feature you build today becomes a feature you’ll maintain tomorrow.</p><p>Every bug you prevent saves hours — or even days — of debugging in the future.</p><p>Professional teams don’t write tests because they’re required.</p><p>They write them because they reduce the cost of change.</p><p>That’s an important distinction.</p><h3>Building a Balanced Testing Strategy</h3><p>Earlier in this series, we introduced the Testing Pyramid.</p><p>Let’s revisit it from a practical perspective.</p><pre>UI Tests<br>Integration Tests<br>Unit Tests</pre><p>A healthy Swift project typically follows these principles:</p><ul><li>Most tests are unit tests.</li><li>Integration tests cover critical interactions.</li><li>UI tests validate key user journeys.</li></ul><p>This balance keeps the test suite fast, reliable, and maintainable.</p><p>Adding more UI tests isn’t always better.</p><p>Adding the right UI tests is.</p><h3>UI Testing with XCUITest</h3><p>Unit tests verify logic.</p><p>UI tests verify experiences.</p><p>Instead of testing individual methods, UI tests simulate how users interact with your application.</p><p>For example:</p><pre>let app = XCUIApplication()<br><br>app.launch()<br>app.buttons[&quot;Login&quot;].tap()<br>app.textFields[&quot;Email&quot;].tap()<br>app.textFields[&quot;Email&quot;].typeText(&quot;john@example.com&quot;)<br>app.secureTextFields[&quot;Password&quot;].typeText(&quot;password123&quot;)<br>app.buttons[&quot;Sign In&quot;].tap()<br>XCTAssertTrue(app.staticTexts[&quot;Welcome&quot;].exists)</pre><p>This test doesn’t care how the login screen is implemented.</p><p>It only cares about the outcome.</p><p>That’s exactly what UI testing should focus on.</p><h3>Avoiding Flaky UI Tests</h3><p>One unstable test can quickly reduce confidence in the entire suite.</p><p>Some common causes include:</p><ul><li>Waiting fixed amounts of time</li><li>Missing accessibility identifiers</li><li>Network-dependent tests</li><li>Animations</li><li>Shared simulator state</li></ul><p>Instead of writing:</p><pre>sleep(5)</pre><p>Prefer waiting for expectations:</p><pre>let welcomeLabel = app.staticTexts[&quot;Welcome&quot;]<br><br>XCTAssertTrue(<br>    welcomeLabel.waitForExistence(timeout: 5)<br>)</pre><p>Deterministic tests are trustworthy tests.</p><h3>Snapshot Testing</h3><p>Sometimes functionality isn’t the problem.</p><p>Appearance is.</p><p>Snapshot testing captures a visual representation of a screen and compares future renders against a known-good baseline.</p><p>If something changes unexpectedly, the test fails.</p><p>Snapshot testing is particularly useful for:</p><ul><li>Complex SwiftUI layouts</li><li>Dark Mode</li><li>Dynamic Type</li><li>Localization</li><li>Multiple device sizes</li></ul><p>It’s an excellent way to catch unintended UI regressions before users do.</p><h3>Performance Testing</h3><p>Correct code isn’t always good code.</p><p>Performance matters.</p><p>Swift provides built-in support for benchmarking.</p><pre>func testSortingPerformance() {<br><br>    measure {<br>        let numbers = (0..&lt;10000).shuffled()<br>        _ = numbers.sorted()<br>    }<br>}</pre><p>Performance tests help detect regressions that functional tests can’t identify.</p><p>As your application evolves, algorithms change.</p><p>Performance tests ensure they don’t become slower without anyone noticing.</p><h3>Code Coverage: What It Really Means</h3><p>One number has probably appeared in every discussion about testing:</p><blockquote><em>Code Coverage</em></blockquote><p>Coverage tells you how much of your code was executed while running tests.</p><p>Notice what it doesn’t tell you.</p><p>It doesn’t tell you whether those tests are meaningful.</p><p>Consider these two projects.</p><p>Project A:</p><ul><li>100% coverage</li><li>Weak assertions</li><li>Poor edge case testing</li></ul><p>Project B:</p><ul><li>75% coverage</li><li>Thorough business logic tests</li><li>Strong edge case coverage</li></ul><p>Which one inspires more confidence?</p><p>Almost certainly Project B.</p><p>Coverage is a useful metric.</p><p>It should never become the goal.</p><p>Behavior is more important than percentages.</p><h3>Continuous Integration</h3><p>Running tests manually works for small projects.</p><p>Professional teams automate everything.</p><p>Every pull request should trigger:</p><ul><li>Build</li><li>Unit Tests</li><li>Integration Tests</li><li>UI Tests (where appropriate)</li><li>Static Analysis</li></ul><p>Only then should code be merged.</p><p>Automation removes uncertainty.</p><p>If every change is validated before merging, production becomes significantly more stable.</p><p>Whether you use GitHub Actions, Xcode Cloud, or another CI platform, the principle remains the same:</p><p>Never rely on someone remembering to run tests.</p><h3>Common Testing Anti-Patterns</h3><p>Good testing is often about avoiding bad habits.</p><p>Here are a few worth watching for.</p><h3>Testing Private Methods</h3><p>Private methods are implementation details.</p><p>Test public behavior instead.</p><h3>Overusing Mocks</h3><p>Mocks are useful.</p><p>Too many mocks create brittle tests that mirror implementation rather than behavior.</p><p>Mock only where necessary.</p><h3>Shared Test State</h3><p>Every test should be independent.</p><p>If one test affects another, debugging becomes painful.</p><h3>Testing Everything</h3><p>Not every line of code deserves a test.</p><p>Focus on:</p><ul><li>Business rules</li><li>Critical workflows</li><li>Edge cases</li><li>Bugs you’ve previously fixed</li></ul><p>Simple property assignments rarely need dedicated tests.</p><h3>What Should You Test?</h3><p>A useful rule of thumb is to prioritize:</p><ol><li>Business logic</li><li>Networking</li><li>Persistence</li><li>Authentication</li><li>Payment flows</li><li>Permissions</li><li>User journeys</li></ol><p>Everything else depends on context.</p><p>Remember:</p><p>Testing is a risk management exercise.</p><p>Invest your effort where failure is most expensive.</p><h3>A Testing Checklist for Every Swift Project</h3><p>Before releasing a feature, ask yourself:</p><ul><li>Does the business logic have unit tests?</li><li>Are edge cases covered?</li><li>Can networking be tested without internet access?</li><li>Are dependencies injected?</li><li>Are UI tests covering critical user flows?</li><li>Are performance-sensitive features benchmarked?</li><li>Do tests run automatically in CI?</li><li>Are tests deterministic?</li></ul><p>If you can answer “yes” to most of these questions, you’re building software that’s easier to maintain and safer to evolve.</p><h3>Final Thoughts</h3><p>Throughout this series, we’ve explored testing from three different perspectives.</p><p>In Part 1, we learned how to write meaningful tests.</p><p>In Part 2, we redesigned our code to make testing possible.</p><p>In this final article, we focused on what separates production-ready applications from hobby projects: strategy.</p><p>Testing isn’t about satisfying a coverage report.</p><p>It isn’t about writing thousands of assertions.</p><p>And it certainly isn’t about proving your code is perfect.</p><p>Testing is about confidence.</p><p>It’s about creating software that welcomes change rather than fears it.</p><p>Because software is never finished.</p><p>It evolves.</p><p>The best engineering teams aren’t the ones who avoid change.</p><p>They’re the ones who can embrace it with confidence.</p><p>And confidence begins with a well-designed test suite.</p><h3>The Complete Series</h3><p>If you’re joining the series here or want to revisit the earlier articles:</p><ul><li><a href="https://medium.com/@sachindrafernando3/modern-testing-in-swift-from-zero-to-confident-f9dfe584dfdc?sharedUserId=sachindrafernando3"><strong>Part 1:</strong> <em>Modern Testing in Swift: From Zero to Confident</em></a></li><li><a href="https://medium.com/@sachindrafernando3/building-testable-swift-applications-0a4e3fd2fd79?sharedUserId=sachindrafernando3"><strong>Part 2:</strong> <em>Building Testable Swift Applications</em></a></li><li><strong>Part 3:</strong> <em>Professional Testing in Swift</em> (this article)</li></ul><p>I hope this series has given you not only the tools to write better tests, but also a deeper understanding of how thoughtful design, effective testing, and a solid testing strategy work together to create reliable Swift applications.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2efdade68df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Testable Swift Applications]]></title>
            <link>https://medium.com/@sachindrafernando3/building-testable-swift-applications-0a4e3fd2fd79?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4e3fd2fd79</guid>
            <category><![CDATA[swift-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[testable-swift-apps]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 19:50:03 GMT</pubDate>
            <atom:updated>2026-06-27T21:07:49.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUZCLYDJRAD3LD-2T-Qblg.png" /></figure><p><strong>This is Part 2 of a 3-part series on testing in Swift.</strong></p><ul><li><a href="https://medium.com/@sachindrafernando3/modern-testing-in-swift-from-zero-to-confident-f9dfe584dfdc?sharedUserId=sachindrafernando3">✅ Part 1: Modern Testing in Swift: From Zero to Confident</a></li><li><strong>Part 2:</strong> Building Testable Swift Applications <em>(you’re here)</em></li><li><a href="https://medium.com/@sachindrafernando3/professional-testing-in-swift-d2efdade68df?sharedUserId=sachindrafernando3">Part 3: Professional Testing in Swift</a></li></ul><p>If you’re new to testing, I recommend starting with Part 1 before continuing.</p><h3>Dependency Injection, Mocks, Async Testing, and Real-World Architecture</h3><blockquote>The biggest obstacle to testing isn’t XCTest or Swift Testing — it’s the way we design our code.</blockquote><p>In the previous article, we explored why testing matters and learned how to write meaningful unit tests using XCTest and Swift Testing.</p><p>Writing tests, however, is only half the story.</p><p>The other half is writing code that <strong>can actually be tested</strong>.</p><p>If you’ve ever tried writing a unit test and found yourself thinking:</p><blockquote><em>“Why is this so difficult?”</em></blockquote><p>The problem often isn’t the test.</p><p>It’s the design of the code you’re trying to test.</p><p>In this article, we’ll learn how to build Swift applications that are naturally testable. We’ll explore dependency injection, protocols, test doubles, asynchronous testing, networking, and architectural patterns that make testing easier instead of harder.</p><p>By the end, you’ll begin seeing your code through a different lens — not just “Does it work?” but “Can I test it?”</p><h3>What Makes Code Difficult to Test?</h3><p>Let’s start with an example.</p><p>Imagine a service responsible for fetching users from an API.</p><pre>final class UserService {<br><br>    private let api = APIClient()<br>    func fetchUsers() async throws -&gt; [User] {<br>        try await api.fetchUsers()<br>    }<br>}</pre><p>At first glance, this looks perfectly reasonable.</p><p>The problem is hidden in one line:</p><pre>private let api = APIClient()</pre><p>UserService creates its own dependency.</p><p>That means:</p><ul><li>You can’t replace the API client.</li><li>You can’t simulate network failures.</li><li>You can’t return fake data.</li><li>Every test depends on a real implementation.</li></ul><p>The service is tightly coupled to APIClient.</p><p>This is one of the most common reasons testing becomes difficult.</p><h3>Dependency Injection: Designing for Flexibility</h3><p>Dependency Injection (DI) simply means <strong>providing dependencies from the outside instead of creating them internally</strong>.</p><p>Let’s refactor our service.</p><p>First, define a protocol:</p><pre>protocol APIClientProtocol {<br>    func fetchUsers() async throws -&gt; [User]<br>}</pre><p>Then make the real client conform to it:</p><pre>final class APIClient: APIClientProtocol {<br>     <br>    func fetchUsers() async throws -&gt; [User] {<br>        // Real networking...<br>    }<br>}</pre><p>Finally, inject the dependency:</p><pre>final class UserService {<br><br>    private let api: APIClientProtocol<br>    init(api: APIClientProtocol) {<br>        self.api = api<br>    }<br>    func fetchUsers() async throws -&gt; [User] {<br>        try await api.fetchUsers()<br>    }<br>}</pre><p>The behavior hasn’t changed.</p><p>The flexibility has.</p><p>Now UserService doesn&#39;t care <em>which</em> API client it receives—it only cares that it conforms to the protocol.</p><p>That small design decision unlocks testability.</p><h3>Why Dependency Injection Matters</h3><p>Dependency injection isn’t just a testing technique.</p><p>It offers several practical benefits:</p><ul><li>Easier unit testing</li><li>Better separation of concerns</li><li>More reusable components</li><li>Easier refactoring</li><li>Improved maintainability</li></ul><p>Perhaps most importantly, it reduces coupling between objects.</p><p>Highly coupled code tends to be brittle.</p><p>Loosely coupled code tends to evolve more gracefully.</p><h3>Introducing Test Doubles</h3><p>Once dependencies can be replaced, we can create simplified versions for testing.</p><p>These are called <strong>test doubles</strong>.</p><p>There are several types, each serving a different purpose.</p><h3>Dummy</h3><p>A placeholder object that’s never actually used.</p><pre>let service = UserService(api: DummyAPIClient())</pre><p>Its only purpose is satisfying a parameter.</p><h3>Stub</h3><p>Returns predefined data.</p><pre>final class StubAPIClient: APIClientProtocol {<br><br>    func fetchUsers() async throws -&gt; [User] {<br>        [<br>            User(name: &quot;Alice&quot;),<br>            User(name: &quot;Bob&quot;)<br>        ]<br>    }<br>}</pre><p>Use stubs when you want predictable responses.</p><h3>Fake</h3><p>A lightweight implementation that behaves like the real thing.</p><p>Instead of using a database, for example, a fake might store data in memory.</p><p>Perfect for integration-style tests.</p><h3>Spy</h3><p>Records interactions.</p><pre>final class SpyAPIClient: APIClientProtocol {<br><br>    private(set) var fetchCalled = false<br>    func fetchUsers() async throws -&gt; [User] {<br>        fetchCalled = true<br>        return []<br>    }<br>}</pre><p>This allows us to verify that a method was called.</p><h3>Mock</h3><p>Defines expectations about interactions.</p><p>Unlike a spy, a mock can fail a test when expectations aren’t met.</p><p>Mocks are powerful, but easy to overuse.</p><p>Whenever possible, prefer testing behavior instead of implementation details.</p><h3>Testing Networking Without the Network</h3><p>One of the biggest mistakes beginners make is testing against a live API.</p><p>Imagine writing this:</p><pre>let users = try await APIClient().fetchUsers()</pre><p>Your tests now depend on:</p><ul><li>Internet connectivity</li><li>Server availability</li><li>API response times</li><li>External infrastructure</li></ul><p>That’s no longer a unit test.</p><p>It’s an integration test.</p><p>Unit tests should be fast, isolated, and deterministic.</p><p>Instead, inject a stub:</p><pre>let service = UserService(api: StubAPIClient())</pre><p>Now every test runs instantly and always produces the same result.</p><h3>Testing Asynchronous Code</h3><p>Modern Swift relies heavily on async/await.</p><p>Fortunately, testing asynchronous code is straightforward.</p><pre>@Test<br>func fetchUsersReturnsExpectedData() async throws {<br><br>    let service = UserService(api: StubAPIClient())<br>    let users = try await service.fetchUsers()<br>    #expect(users.count == 2)<br>}</pre><p>Or using XCTest:</p><pre>func testFetchUsers() async throws {<br><br>    let service = UserService(api: StubAPIClient())<br>    let users = try await service.fetchUsers()<br>    XCTAssertEqual(users.count, 2)<br>}</pre><p>No expectations.</p><p>No callbacks.</p><p>No completion handlers.</p><p>Just clean, readable asynchronous tests.</p><h3>SwiftUI and Testability</h3><p>One question comes up frequently:</p><blockquote><em>“Should I test my SwiftUI views?”</em></blockquote><p>Usually, not directly.</p><p>Instead, test the logic behind the views.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7An0wn_GCXywKH5nSWLSg.png" /></figure><p>Views should display state.</p><p>Business logic should determine state.</p><p>The majority of your unit tests should target ViewModels and services rather than view hierarchies.</p><h3>A Note on Architecture</h3><p>Architecture isn’t about choosing the “best” pattern.</p><p>It’s about choosing one that makes change easier.</p><p>Whether you’re using:</p><ul><li>MVC</li><li>MVVM</li><li>Clean Architecture</li><li>The Composable Architecture</li></ul><p>The same principle applies:</p><p><strong>Dependencies should flow inward, not outward.</strong></p><p>When components own their own dependencies, testing becomes difficult.</p><p>When dependencies are injected, testing becomes straightforward.</p><p>Good architecture and good testing naturally reinforce one another.</p><h3>Refactoring Toward Testability</h3><p>When adding tests to an existing project, don’t aim for perfection immediately.</p><p>Instead, look for opportunities to improve incrementally.</p><p>Ask yourself:</p><ul><li>Can this dependency be injected?</li><li>Can this class depend on a protocol instead of a concrete type?</li><li>Can I separate business logic from UI?</li><li>Can I remove hidden state?</li></ul><p>Small improvements accumulate into a codebase that’s easier to understand, extend, and test.</p><h3>Key Takeaways</h3><p>By now, you should recognize that writing tests isn’t the difficult part.</p><p>Designing software that welcomes testing is.</p><p>Here’s what we’ve covered:</p><ul><li>Dependency Injection decouples components and enables testing.</li><li>Protocols make dependencies replaceable.</li><li>Test doubles provide predictable, isolated behavior.</li><li>Async/await makes asynchronous testing significantly cleaner.</li><li>SwiftUI logic belongs in ViewModels, where it can be tested effectively.</li><li>Good architecture naturally leads to more testable applications.</li></ul><p>Testing isn’t something you add after development.</p><p>It’s something your design should make possible from the beginning.</p><h3>Continue the Series</h3><p>You’ve learned how good architecture makes testing significantly easier.</p><p>In the final article, we’ll move beyond writing tests and explore how professional teams maintain confidence as their applications grow.</p><p>We’ll cover:</p><ul><li>UI Testing with XCUITest</li><li>Snapshot Testing</li><li>Performance Testing</li><li>Code Coverage</li><li>Continuous Integration</li><li>Long-term testing strategy</li></ul><p><a href="https://medium.com/@sachindrafernando3/professional-testing-in-swift-d2efdade68df?sharedUserId=sachindrafernando3">➡️ <strong>Read Part 3:</strong> <em>Professional Testing in Swift</em></a></p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4e3fd2fd79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Testing in Swift: From Zero to Confident]]></title>
            <link>https://medium.com/@sachindrafernando3/modern-testing-in-swift-from-zero-to-confident-f9dfe584dfdc?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9dfe584dfdc</guid>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift-testing]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 17:48:12 GMT</pubDate>
            <atom:updated>2026-06-27T22:18:46.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxqThYlCboHnnniEJpw2fA.png" /></figure><blockquote><strong><em>This article is Part 1 of a 3 part series on modern testing in Swift.</em></strong></blockquote><ul><li><strong>Part 1: Modern Testing in Swift: From Zero to Confident <em>(you’re here)</em></strong></li><li><a href="https://medium.com/@sachindrafernando3/building-testable-swift-applications-0a4e3fd2fd79?sharedUserId=sachindrafernando3"><strong>Part 2: Building Testable Swift Applications</strong></a></li><li><a href="https://medium.com/@sachindrafernando3/professional-testing-in-swift-d2efdade68df?sharedUserId=sachindrafernando3"><strong>Part 3: Professional Testing in Swift</strong></a></li></ul><blockquote>Testing is not about proving your code works. It’s about proving it will keep working when everything around it changes.</blockquote><p>Every Swift developer eventually runs into the same situation.</p><p>You ship a feature. Everything works. You feel confident.</p><p>Then, days later, something unrelated breaks, a login flow stops working, a list renders incorrectly, or an API response silently fails.</p><p>The frustrating part?</p><p>You didn’t touch that code.</p><p>This is exactly where testing stops being a “nice to have” and becomes a core part of how you build software.</p><p>In this article, we’ll build a strong foundation for testing in Swift, not just syntax, but mindset, structure, and practical usage, using both <strong>XCTest</strong> and <strong>Swift Testing</strong>.</p><p>By the end, you’ll understand not only how to write tests, but why they fundamentally change the way you build and maintain applications.</p><h3>Why Testing Exists (and What It Actually Solves)</h3><p>Let’s start with a simple truth:</p><p><strong>Testing is not about finding bugs. It’s about preventing regressions.</strong></p><p>A regression happens when something that used to work stops working because of a change somewhere else in the system.</p><p>And most real-world bugs are exactly that, regressions.</p><p>Without tests, development usually looks like this:</p><ul><li>Add a feature</li><li>Manually test what you changed</li><li>Ship</li><li>Hope nothing else broke</li></ul><p>This works… until your codebase grows.</p><p>Then every change becomes a gamble.</p><p>With tests, the workflow changes:</p><ul><li>Add a feature</li><li>Run tests</li><li>Get immediate feedback if something broke</li><li>Fix it before shipping</li></ul><p>That’s the difference between:</p><blockquote><strong><em>hope-driven development</em></strong><em> and </em><strong><em>confidence-driven development</em></strong></blockquote><h3>The Testing Pyramid (A Mental Model That Matters)</h3><p>Before writing code, it’s important to understand how tests are structured in real systems.</p><p>Most mature Swift codebases follow a simple model:</p><pre>UI Tests<br>Integration Tests<br>Unit Tests</pre><h3>Unit Tests (Foundation Layer)</h3><ul><li>Fast</li><li>Reliable</li><li>Easy to maintain</li><li>Should cover most of your logic</li></ul><h3>Integration Tests (Middle Layer)</h3><ul><li>Test how components work together</li><li>Slightly slower</li><li>Validate real-world flows</li></ul><h3>UI Tests (Top Layer)</h3><ul><li>Slowest</li><li>Most fragile</li><li>Simulate user behavior</li></ul><p>A healthy test suite is <strong>bottom-heavy</strong>.</p><p>If most of your tests are UI tests, your suite will eventually become slow, flaky, and painful to maintain.</p><h3>XCTest vs Swift Testing</h3><p>Swift currently has two main testing frameworks:</p><h3>XCTest (The Classic Approach)</h3><p>The traditional and widely used framework:</p><pre>func testAddition() {<br>    XCTAssertEqual(2 + 2, 4)<br>}</pre><p>It is:</p><ul><li>Stable</li><li>Mature</li><li>Battle-tested in production</li></ul><p>Most existing iOS codebases use XCTest today.</p><h3>Swift Testing (Modern Approach)</h3><p>A newer, more expressive framework:</p><pre>@Test<br>func addition() {<br>    #expect(2 + 2 == 4)<br>}</pre><p>It introduces:</p><ul><li>Cleaner syntax</li><li>Macro-based assertions</li><li>More readable tests</li><li>Better alignment with modern Swift features</li></ul><h3>Which One Should You Use?</h3><p>There is no strict rule.</p><ul><li>Existing projects → XCTest</li><li>New projects → Swift Testing</li><li>Large codebases → both can coexist</li></ul><p>In practice, many teams gradually adopt Swift Testing while keeping XCTest in place.</p><h3>Creating Your First Test Target</h3><p>Let’s get practical.</p><p>In Xcode:</p><ol><li>Go to <strong>File → New → Target</strong></li><li>Select <strong>Unit Testing Bundle</strong></li><li>Xcode creates a Tests directory automatically</li></ol><p>Your project structure becomes:</p><pre>MyApp/<br>MyAppTests/</pre><p>Now write your first test:</p><pre>import XCTest<br><br>final class MyAppTests: XCTestCase {<br>    func testExample() {<br>        XCTAssertEqual(1 + 1, 2)<br>    }<br>}</pre><p>Run tests using:</p><blockquote><strong><em>Cmd + U</em></strong></blockquote><p>If it passes, congratulations.</p><p>You’ve just added automated validation to your codebase.</p><p>More importantly, you’ve created your first layer of safety.</p><h3>The Anatomy of a Good Test</h3><p>Every well-written test follows a simple structure:</p><h3>Arrange → Act → Assert</h3><h3>Example:</h3><pre>func testTotalPriceCalculation() {<br>    // Arrange<br>    let cart = Cart()<br>    cart.addItem(price: 10)<br>    cart.addItem(price: 20)<br>// Act<br>    let total = cart.totalPrice()<br>    // Assert<br>    XCTAssertEqual(total, 30)<br>}</pre><h3>Why this matters</h3><p>This structure ensures tests are:</p><ul><li>Easy to read</li><li>Easy to debug</li><li>Easy to maintain</li></ul><p>If a test is hard to understand, it will eventually be ignored, and ignored tests are useless.</p><h3>Writing Meaningful Unit Tests</h3><p>A good unit test is:</p><ul><li>Fast (runs in milliseconds)</li><li>Deterministic (same result every time)</li><li>Isolated (no external dependencies)</li><li>Focused (tests one behavior only)</li></ul><p>Let’s look at a simple example:</p><pre>struct DiscountCalculator {<br>    func applyDiscount(to price: Double, isMember: Bool) -&gt; Double {<br>        isMember ? price * 0.9 : price<br>    }<br>}</pre><p>Now the test:</p><pre>func testMemberReceivesDiscount() {<br>    let calculator = DiscountCalculator()<br>    <br>    let result = calculator.applyDiscount(to: 100, isMember: true)<br>    XCTAssertEqual(result, 90)<br>}</pre><p>This test matters because it locks in behavior.</p><p>If someone changes discount logic later, this test will immediately catch it.</p><p>That’s the real value of testing.</p><h3>Common Mistakes Developers Make</h3><p>Most developers struggle with testing in predictable ways.</p><h3>1. Testing too many things at once</h3><p>Bad:</p><pre>func testEverything() { }</pre><p>Good:</p><ul><li>One behavior per test</li></ul><h3>2. Shared state between tests</h3><p>Tests should never depend on each other.</p><p>Each test must be independent.</p><h3>3. Testing implementation instead of behavior</h3><p>Don’t test <em>how</em> something works internally.</p><p>Test <em>what it does</em> externally.</p><h3>4. Ignoring edge cases</h3><p>Real-world bugs often live here:</p><ul><li>empty inputs</li><li>zero values</li><li>negative numbers</li><li>nil values</li><li>invalid data</li></ul><h3>A Shift in Thinking</h3><p>This is the most important idea in this entire article:</p><blockquote><em>Tests are not about proving correctness. They are about protecting future change.</em></blockquote><p>When you write a test, you are not thinking about today’s code.</p><p>You are protecting tomorrow’s developer, which is often just future you.</p><p>That’s why tests feel like overhead at first… but become acceleration later.</p><h3>Quick Exercise (Do This Before Moving On)</h3><p>Consider this function:</p><pre>func isValidPassword(_ password: String) -&gt; Bool {<br>    return password.count &gt;= 8<br>}</pre><p>Now think:</p><ul><li>What should happen with &quot;1234567&quot;?</li><li>What about &quot;12345678&quot;?</li><li>What about &quot;&quot;?</li></ul><p>Write the tests first.</p><p>Then implement or refine behavior.</p><p>This is the foundation of test-driven thinking.</p><h3>Key Takeaways</h3><p>If you remember nothing else, remember this:</p><ul><li>Testing is about preventing regressions, not finding bugs</li><li>Most bugs happen when code changes elsewhere</li><li>Unit tests form the foundation of a stable system</li><li>XCTest and Swift Testing both matter</li><li>Good tests are simple, isolated, and focused</li><li>Testing changes your development mindset entirely</li></ul><h3>Continue the Series</h3><p>You’ve learned why testing matters and how to write your first unit tests.</p><p>In <a href="https://medium.com/@sachindrafernando3/building-testable-swift-applications-0a4e3fd2fd79?sharedUserId=sachindrafernando3"><strong>Part 2: Building Testable Swift Applications</strong></a>, we’ll explore how to write code that’s easy to test using:</p><ul><li>Dependency Injection</li><li>Protocol-oriented design</li><li>Test doubles</li><li>Async testing</li><li>Real-world architecture</li></ul><p><a href="https://medium.com/@sachindrafernando3/building-testable-swift-applications-0a4e3fd2fd79?sharedUserId=sachindrafernando3">➡️ <strong>Read Part 2:</strong> <em>Building Testable Swift Applications</em></a></p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9dfe584dfdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Swift Concurrency: Combine vs async/await and When to Use Each]]></title>
            <link>https://medium.com/@sachindrafernando3/modern-swift-concurrency-combine-vs-async-await-and-when-to-use-each-a35b8b513b2b?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a35b8b513b2b</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[await]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 22:36:39 GMT</pubDate>
            <atom:updated>2026-06-25T22:36:39.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGWJW3Clvxih5cQyOYL3-A.png" /></figure><p>Swift developers today have access to two powerful concurrency models: <strong>Combine</strong> and <strong>async/await</strong>. While both address asynchronous programming, they are designed with fundamentally different mental models.</p><p>Understanding when to use each is not about preference; it is about selecting the right abstraction for the problem at hand.</p><p>This article breaks down both approaches clearly, compares their strengths, and provides practical guidance for real-world iOS development.</p><h3>Two Different Concurrency Philosophies</h3><p>At a high level:</p><ul><li><strong>async/await</strong> models <em>asynchronous tasks that produce a single result</em></li><li><strong>Combine</strong> models <em>streams of values over time</em></li></ul><p>This distinction is the key to understanding everything else.</p><h3>async/await: Structured Concurrency for Single Results</h3><p>async/await is built on Swift’s structured concurrency system. It allows asynchronous code to be written in a synchronous style, improving readability and maintainability.</p><h4>Example: Fetching Data</h4><pre>func fetchUser() async throws -&gt; User {<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return try JSONDecoder().decode(User.self, from: data)<br>}</pre><h4>Usage</h4><pre>Task {<br>    do {<br>        let user = try await fetchUser()<br>        print(user.name)<br>    } catch {<br>        print(error)<br>    }<br>}</pre><h4>Key Characteristics</h4><ul><li>Returns a single value or throws an error</li><li>Sequential, linear flow</li><li>Easy error handling using try/catch</li><li>Built-in cancellation support via Task</li></ul><h4>Best suited for:</h4><ul><li>Network requests</li><li>Database queries</li><li>File I/O</li><li>Authentication flows</li></ul><p>In essence, async/await is ideal when you are waiting for <strong>one result in the future</strong>.</p><h3>Combine: Declarative Reactive Streams</h3><p>Combine introduces a reactive programming model based on <strong>publishers and subscribers</strong>. Instead of returning a single value, a publisher emits a sequence of values over time.</p><h4>Example: Data Task Publisher</h4><pre>URLSession.shared.dataTaskPublisher(for: url)<br>    .map(\.data)<br>    .decode(type: User.self, decoder: JSONDecoder())<br>    .sink(<br>        receiveCompletion: { completion in<br>            print(completion)<br>        },<br>        receiveValue: { user in<br>            print(user)<br>        }<br>    )<br>    .store(in: &amp;cancellables)</pre><h4>Key Characteristics</h4><ul><li>Emits multiple values over time</li><li>Supports rich transformation operators (map, filter, flatMap, debounce, etc.)</li><li>Built for event-driven programming</li><li>Requires explicit memory management via AnyCancellable</li></ul><h4>Best suited for:</h4><ul><li>Search-as-you-type</li><li>UI event handling</li><li>Real-time updates</li><li>Timers and notifications</li><li>Complex data pipelines</li></ul><p>Combine is most powerful when working with <strong>continuous streams of events</strong>.</p><h3>Core Difference: Single Result vs Continuous Stream</h3><p>The simplest way to distinguish the two is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6f7a49770c99ca1258ebb89cccb7163/href">https://medium.com/media/a6f7a49770c99ca1258ebb89cccb7163/href</a></iframe><p>This difference influences architecture, not just syntax.</p><h3>Practical Scenario: Search Feature</h3><p>Consider implementing a search bar that reacts to user input.</p><h4>Requirements:</h4><ul><li>Wait for user to stop typing (debounce)</li><li>Ignore duplicate input</li><li>Cancel previous requests</li><li>Only process latest query</li></ul><h4>Combine Approach</h4><pre>searchTextPublisher<br>    .debounce(for: .milliseconds(300), scheduler: RunLoop.main)<br>    .removeDuplicates()<br>    .flatMap { query in<br>        search(query)<br>    }</pre><p>This declaratively expresses the entire pipeline.</p><h3>async/await Approach</h3><p>Using async/await, you must manually manage:</p><ul><li>Debouncing (timers or Task.sleep)</li><li>Cancellation of previous tasks</li><li>State synchronization</li></ul><p>Example (simplified):</p><pre>func performSearch(_ query: String) async {<br>    currentTask?.cancel()<br>    <br>    currentTask = Task {<br>        try await Task.sleep(nanoseconds: 300_000_000)<br>        guard !Task.isCancelled else { return }<br>        let results = try await search(query)<br>        print(results)<br>    }<br>}</pre><p>While achievable, it introduces more boilerplate and manual control logic.</p><h3>Interoperability: You Don’t Have to Choose One</h3><p>Modern Swift allows Combine and async/await to work together.</p><h4>Converting Combine → async/await</h4><pre>for try await value in publisher.values {<br>    print(value)<br>}</pre><h4>Converting async → Combine</h4><p>You can wrap async work inside a publisher when integrating with legacy Combine-based systems.</p><p>This makes gradual migration possible instead of requiring full rewrites.</p><h3>Architectural Guidance</h3><p>A practical rule used in many production iOS applications:</p><h4>Prefer async/await when:</h4><ul><li>You are modeling a single asynchronous operation</li><li>The flow is linear and finite</li><li>You want simpler, more readable code</li></ul><h4>Prefer Combine when:</h4><ul><li>You are modeling multiple values over time</li><li>You need operator-based transformations</li><li>You are working with event-driven UI systems</li></ul><p>In modern architectures, it is common for both to coexist:</p><ul><li>async/await for networking and business logic</li><li>Combine for UI binding and reactive streams</li></ul><h3>Conclusion</h3><p>Combine and async/await are not competing technologies — they are complementary tools designed for different levels of abstraction.</p><ul><li>async/await simplifies asynchronous code into readable, structured flows.</li><li>Combine enables powerful composition of event streams.</li></ul><p>The real skill is not choosing one over the other, but recognizing the nature of the problem:</p><blockquote><em>Is this a single future value, or a continuous stream of values?</em></blockquote><p>Once that distinction is clear, the right solution becomes obvious.</p><p>And in most real-world Swift applications, using both together leads to the most scalable and maintainable architecture.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35b8b513b2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The CI/CD Workflow Every Swift Developer Should Know]]></title>
            <link>https://medium.com/@sachindrafernando3/the-ci-cd-workflow-every-swift-developer-should-know-281a37b53c06?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/281a37b53c06</guid>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[dc]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[ci]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 22:33:54 GMT</pubDate>
            <atom:updated>2026-06-24T22:33:54.014Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Stop manually archiving builds and uploading them to TestFlight. Here’s how modern iOS teams automate everything.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKtOjWqhAushU0oIKEhuEw.png" /></figure><h3>Introduction</h3><p>Many iOS developers spend years mastering Swift, SwiftUI, UIKit, and Apple’s frameworks, but when it comes to releasing apps, the workflow often looks like this:</p><ul><li>Build locally</li><li>Fix build errors</li><li>Archive the app</li><li>Upload to TestFlight</li><li>Wait</li><li>Repeat</li></ul><p>It works… until you’re on a team, shipping multiple releases every week.</p><p>That’s where Continuous Integration (CI) and Continuous Delivery (CD) become game changers.</p><p>In this article, we’ll build a practical CI/CD workflow for a Swift project and explore the tools professional iOS teams use every day.</p><h3>What is CI/CD?</h3><p>CI/CD is simply the automation of repetitive development tasks.</p><p>Instead of manually building and testing your app, every code change automatically triggers a pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjA54xS9JicB-g2It7SBaw.png" /></figure><p>If anything fails, the pipeline stops immediately.</p><h3>Step 1 — Continuous Integration</h3><p>Every Pull Request should automatically:</p><ul><li>Build the project</li><li>Resolve Swift Packages</li><li>Run unit tests</li><li>Run UI tests (optional)</li><li>Check code style with SwiftLint</li><li>Generate code coverage</li></ul><p>This gives developers confidence before merging.</p><h3>Step 2 — Continuous Delivery</h3><p>Once the code reaches the main branch, the release pipeline begins.</p><p>A typical workflow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExM5aM6_--w8pP891fr4aQ.png" /></figure><p>No one should need to open Xcode just to distribute a beta build.</p><h3>Essential Tools</h3><p>A modern Swift CI/CD pipeline often includes:</p><ul><li>GitHub Actions</li><li>Xcode Cloud</li><li>Bitrise</li><li>Fastlane</li><li>SwiftLint</li><li>SwiftFormat</li><li>XCTest</li></ul><p>You don’t need all of them. Start simple and automate incrementally.</p><h3>Example GitHub Actions Workflow</h3><p>Include a complete YAML workflow that:</p><ul><li>Builds the project</li><li>Runs tests</li><li>Caches Swift Package Manager dependencies</li><li>Fails on lint issues</li></ul><p>This provides a strong starting point for readers.</p><h3>Automating Releases with Fastlane</h3><p>Fastlane can:</p><ul><li>Increment build numbers</li><li>Create archives</li><li>Upload to TestFlight</li><li>Upload to the App Store</li><li>Manage screenshots</li><li>Generate release notes</li></ul><p>A release can become as simple as:</p><p>Fastlane beta</p><h3>Best Practices</h3><ul><li>Never merge code that doesn’t build.</li><li>Run tests on every Pull Request.</li><li>Keep secrets out of the repository.</li><li>Cache dependencies to speed up builds.</li><li>Use semantic versioning.</li><li>Automate as much of the release process as possible.</li></ul><h3>Final Thoughts</h3><p>CI/CD isn’t just about automation.</p><p>It’s about making releases predictable, reducing human error, and giving developers fast feedback so they can focus on building features instead of clicking through release steps.</p><p>Whether you’re working solo or on a large team, investing a few hours in a CI/CD pipeline can save countless hours over the lifetime of your project.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281a37b53c06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Swift Encourages Protocol-Oriented Programming (and What It Actually Means)]]></title>
            <link>https://medium.com/@sachindrafernando3/why-swift-encourages-protocol-oriented-programming-and-what-it-actually-means-8d8540d12f9d?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8540d12f9d</guid>
            <category><![CDATA[protocol-oriented-mvvm]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 19:02:58 GMT</pubDate>
            <atom:updated>2026-06-23T19:02:58.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnRomyzgvIBUCPAIffEgeQ.png" /></figure><p>If you’ve been learning Swift for a while, there’s a moment that usually feels a bit confusing.</p><p>You start with classes, inheritance, and familiar object-oriented thinking… and then suddenly you encounter protocols everywhere.</p><p>At first, it feels like just another feature.</p><p>But the more you use Swift, the more it feels like something deeper is going on:</p><blockquote><em>Swift doesn’t just </em>support<em> protocols — it gently pushes you toward them.</em></blockquote><p>So what’s really happening here?</p><h3>The Inheritance Trap (That Most Languages Start With)</h3><p>Let’s begin with something familiar.</p><p>In many object-oriented languages, we naturally model systems using inheritance:</p><ul><li>Animal</li><li>Dog</li><li>Cat</li><li>Bird</li></ul><p>At first glance, this looks clean and logical.</p><p>But as systems grow, cracks start to appear.</p><h3>The problems begin subtly:</h3><p><strong>1. Deep inheritance trees get fragile</strong><br> A small change in a base class can ripple through everything below it.</p><p><strong>2. Subclasses inherit too much</strong><br> A child class often gets behavior it doesn’t actually need.</p><p><strong>3. Real-world behavior doesn’t fit clean hierarchies</strong><br> What if something needs to both “fly” and “swim”? Inheritance quickly starts to feel restrictive.</p><p>This is what developers often call the <strong>fragile base class problem</strong>.</p><p>And this is exactly the kind of design Swift tries to move away from.</p><h3>Swift’s Alternative Thinking: “What Can It Do?”</h3><p>Instead of asking:</p><blockquote><em>“What is this thing?”</em></blockquote><p>Swift encourages you to ask:</p><blockquote><em>“What can this thing do?”</em></blockquote><p>That shift leads directly to <strong>protocols</strong>.</p><p>A protocol defines a set of rules or capabilities:</p><pre>protocol Drivable {<br>    func drive()<br>}</pre><p>Notice what this does <em>not</em> do:</p><ul><li>It does not define structure</li><li>It does not define inheritance</li><li>It does not force a relationship</li></ul><p>It only defines behavior.</p><h3>The Real Power: Anything Can Adopt a Protocol</h3><p>Now things start to get interesting.</p><p>A struct can adopt it:</p><pre>struct Car: Drivable {<br>    func drive() {<br>        print(&quot;Driving a car&quot;)<br>    }<br>}</pre><p>A class can adopt it:</p><pre>class Truck: Drivable {<br>    func drive() {<br>        print(&quot;Driving a truck&quot;)<br>    }<br>}</pre><p>Suddenly:</p><ul><li>No inheritance required</li><li>No rigid hierarchy</li><li>No forced relationships</li></ul><p>Just behavior.</p><h3>Why Swift Prefers Protocol-Oriented Design</h3><p>At this point, you might wonder:</p><blockquote><em>Is Swift trying to replace OOP completely?</em></blockquote><p>Not really.</p><p>Instead, Swift encourages a different mindset.</p><h4>1. Composition over inheritance</h4><p>Instead of forcing types into hierarchies, Swift encourages building behavior from smaller pieces.</p><p>So instead of:</p><blockquote><em>“A Dog is an Animal”</em></blockquote><p>You start thinking:</p><blockquote><em>“A Dog can bark, walk, and eat”</em></blockquote><pre>protocol Barkable {<br>    func bark()<br>}<br><br>protocol Walkable {<br>    func walk()<br>}</pre><p>Now behavior becomes modular and reusable.</p><h4>2. Multiple behaviors without complexity</h4><p>In many languages, multiple inheritance is either forbidden or dangerous.</p><p>Swift solves this differently.</p><p>A type can conform to multiple protocols:</p><pre>struct Dog: Barkable, Walkable {<br>    func bark() { print(&quot;Woof&quot;) }<br>    func walk() { print(&quot;Walking&quot;) }<br>}</pre><p>No complexity. No diamond problem. Just composition.</p><h4>3. Protocols work beautifully with structs</h4><p>Swift heavily promotes <strong>value types</strong> like structs and enums.</p><p>Why?</p><p>Because they:</p><ul><li>Avoid shared mutable state</li><li>Are safer in concurrent environments</li><li>Behave predictably</li></ul><p>And protocols allow them to still behave polymorphically — without inheritance.</p><h4>4. Protocol extensions: shared behavior without base classes</h4><p>Here’s where Swift gets especially powerful.</p><p>You can add default behavior directly to protocols:</p><pre>extension Drivable {<br>    func startEngine() {<br>        print(&quot;Engine started&quot;)<br>    }<br>}</pre><p>Now any conforming type automatically gets this functionality.</p><pre>struct Bike: Drivable {<br>    func drive() {<br>        print(&quot;Riding a bike&quot;)<br>    }<br>}<br>let bike = Bike()<br>bike.startEngine() // default implementation</pre><p>No base class needed. No duplication.</p><h3>But Here’s the Important Truth: Swift Is NOT Purely Protocol-Oriented</h3><p>This is where many explanations go wrong.</p><p>Swift is <strong>not a protocol-only language</strong>.</p><p>It is a <strong>multi-paradigm language</strong>, meaning it supports:</p><ul><li>Object-oriented programming (classes and inheritance)</li><li>Protocol-oriented programming</li><li>Functional programming concepts (map, filter, reduce)</li><li>Generic programming</li></ul><p>So yes, you <em>can</em> still use inheritance:</p><pre>class Animal {<br>    func speak() {<br>        print(&quot;Some sound&quot;)<br>    }<br>}<br>class Dog: Animal {<br>    override func speak() {<br>        print(&quot;Bark&quot;)<br>    }<br>}</pre><p>And in many real-world frameworks like UIKit, class-based inheritance is still heavily used.</p><p>So the key idea is:</p><blockquote><em>Swift doesn’t remove OOP, it balances it with better alternatives.</em></blockquote><h3>When Protocols Shine (and When They Don’t)</h3><p>Like any tool, protocols are powerful, but not always the answer.</p><h3>Use protocols when:</h3><ul><li>You want flexible, reusable behavior</li><li>You want to reduce coupling between components</li><li>You’re designing APIs or frameworks</li><li>You want easy testability (mocking becomes simple)</li></ul><h3>Be careful when:</h3><ul><li>You create too many tiny, meaningless protocols</li><li>A simple class would be clearer</li><li>The abstraction doesn’t actually simplify anything</li></ul><p>Sometimes:</p><blockquote><em>Simpler is better than “perfectly abstract.”</em></blockquote><h3>A Real-World Example: Payment System</h3><p>Let’s make everything concrete.</p><p>Imagine you’re building a payment system.</p><p>Start with a protocol:</p><pre>protocol PaymentMethod {<br>    func pay(amount: Double)<br>}</pre><p>Now multiple implementations:</p><pre>struct CardPayment: PaymentMethod {<br>    func pay(amount: Double) {<br>        print(&quot;Paid \(amount) using card&quot;)<br>    }<br>}<br>struct ApplePay: PaymentMethod {<br>    func pay(amount: Double) {<br>        print(&quot;Paid \(amount) using Apple Pay&quot;)<br>    }<br>}</pre><p>Now your checkout system doesn’t care about the implementation:</p><pre>struct Checkout {<br>    let method: PaymentMethod<br>    func complete(amount: Double) {<br>        method.pay(amount: amount)<br>    }<br>}</pre><p>What did we gain?</p><ul><li>Easy extensibility (add new payment methods anytime)</li><li>Loose coupling (Checkout doesn’t change)</li><li>Testability (mock PaymentMethod easily)</li></ul><p>This is protocol-oriented programming in real life.</p><h3>Final Thought</h3><p>Swift didn’t replace object-oriented programming.</p><p>Instead, it quietly introduced a better question:</p><blockquote><em>Not “what does this object inherit?”<br> But “what behaviors can we compose?”</em></blockquote><p>That shift is what makes Swift feel different.</p><p>And once you start thinking in protocols, you don’t really go back; you just start designing systems in smaller, more flexible pieces.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8540d12f9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI + UIKit: Building Modern iOS Apps Without Choosing Sides]]></title>
            <link>https://medium.com/@sachindrafernando3/swiftui-uikit-building-modern-ios-apps-without-choosing-sides-32f80433b8c6?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/32f80433b8c6</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 09:38:20 GMT</pubDate>
            <atom:updated>2026-06-21T08:08:17.991Z</atom:updated>
            <content:encoded><![CDATA[<p><em>SwiftUI isn’t here to replace UIKit overnight. The best iOS developers know how to make them work together.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGc6KWJ4QbKUe9W27Of9Kg.png" /></figure><h3>Introduction</h3><p>When SwiftUI was introduced at WWDC 2019, many developers thought UIKit’s days were numbered.</p><p>Fast forward to today, and that’s clearly not what happened.</p><p>Most production iOS applications still contain a significant amount of UIKit. New features are often written in SwiftUI while legacy screens continue to run on UIKit. Even Apple mixes both frameworks in many of its own applications.</p><p>The reality is simple:</p><blockquote><em>Modern iOS development isn’t about choosing SwiftUI or UIKit. It’s about knowing how to bridge them together seamlessly.</em></blockquote><p>In this article, we’ll explore both directions:</p><ul><li>Embedding SwiftUI inside UIKit</li><li>Embedding UIKit inside SwiftUI</li></ul><p>Along the way, we’ll discuss when each approach makes sense and the common pitfalls to avoid.</p><h3>Understanding the Relationship</h3><p>Think of the frameworks like this:</p><pre>UIKit<br>├── UIViewController<br>├── UIView<br>├── UINavigationController<br>└── Storyboards/XIBs</pre><pre>SwiftUI<br>├── View<br>├── State<br>├── Binding<br>├── Environment<br>└── Declarative Rendering</pre><p>UIKit is imperative.</p><p>You tell the interface <strong>what to do</strong>.</p><pre>label.text = &quot;Hello&quot;<br>button.isHidden = true</pre><p>SwiftUI is declarative.</p><p>You describe <strong>what the UI should look like</strong> based on the current state.</p><pre>Text(title)</pre><pre>if isLoading {<br>    ProgressView()<br>}</pre><p>Since many apps contain both frameworks, Apple provides official bridges between them.</p><h3>1. Using SwiftUI inside UIKit</h3><p>This is probably the most common migration strategy.</p><p>Imagine your application has 100 UIKit screens.</p><p>You don’t want to rewrite everything.</p><p>Instead, you create new screens in SwiftUI while keeping the existing UIKit architecture.</p><p>Apple introduced <strong>UIHostingController</strong> exactly for this purpose.</p><h4>What is UIHostingController?</h4><p>UIHostingController is a bridge that wraps any SwiftUI view inside a normal UIViewController.</p><p>That means UIKit can present it, push it onto a navigation stack, or display it modally.</p><pre>UIKit<br>      ↓<br>UIHostingController<br>      ↓<br>SwiftUI View</pre><h4>Example</h4><p>Suppose we have a SwiftUI view.</p><pre>struct ProfileView: View {<br>  var body: some View {<br>        VStack {<br>            Image(systemName: &quot;person.circle.fill&quot;)<br>                .font(.system(size: 70))<br>            Text(&quot;John Doe&quot;)<br>                .font(.title)<br>        }<br>    }<br>}</pre><p>Now present it from UIKit.</p><pre>let profileView = ProfileView()<br>let hostingController = UIHostingController(rootView: profileView)<br>navigationController?.pushViewController(hostingController, animated: true)</pre><p>That’s it.</p><p>UIKit treats it exactly like any other view controller.</p><h4>Present Modally</h4><pre>let hostingController = UIHostingController(rootView: SettingsView())<br>present(hostingController, animated: true)</pre><p>No extra setup required.</p><h3>Embedding SwiftUI as a Child View</h3><p>Sometimes you don’t want an entire screen.</p><p>Maybe only a small portion should be SwiftUI.</p><pre>let hostingController = UIHostingController(rootView: HeaderView())<br>addChild(hostingController)<br>view.addSubview(hostingController.view)<br>hostingController.didMove(toParent: self)</pre><p>Now SwiftUI becomes just another child view inside UIKit.</p><p>This approach is perfect for gradually modernizing large applications.</p><h4>Passing Data from UIKit to SwiftUI</h4><p>Passing data is straightforward.</p><pre>struct UserView: View {<br>  let username: String<br>    var body: some View {<br>        Text(username)<br>    }<br>}</pre><p>UIKit:</p><pre>let vc = UIHostingController(<br>    rootView: UserView(username: &quot;Alex&quot;)<br>)</pre><p>The SwiftUI view receives the data naturally.</p><h4>Updating SwiftUI from UIKit</h4><p>If your SwiftUI screen needs to react to changing data, use an ObservableObject.</p><pre>class UserViewModel: ObservableObject {<br>  @Published var name = &quot;John&quot;<br>}</pre><p>SwiftUI:</p><pre>struct UserView: View {<br>  @ObservedObject var viewModel: UserViewModel<br>    var body: some View {<br>        Text(viewModel.name)<br>    }<br>}</pre><p>UIKit:</p><pre>viewModel.name = &quot;Emily&quot;</pre><p>SwiftUI automatically refreshes.</p><p>No reloadData().</p><p>No setNeedsLayout().</p><p>No manual UI updates.</p><h3>2. Using UIKit inside SwiftUI</h3><p>Sometimes SwiftUI doesn’t offer a component you need.</p><p>Maybe you’re using:</p><ul><li>MKMapView</li><li>WKWebView</li><li>UITextView</li><li>PDFKit</li><li>Camera</li><li>Third-party UIKit SDKs</li></ul><p>This is where UIViewRepresentable comes in.</p><h4>What is UIViewRepresentable?</h4><p>It allows SwiftUI to wrap any UIKit UIView.</p><pre>SwiftUI<br>      ↓<br>UIViewRepresentable<br>      ↓<br>UIKit View</pre><h4>Example: UILabel</h4><pre>struct CustomLabel: UIViewRepresentable {<br>  func makeUIView(context: Context) -&gt; UILabel {<br>        let label = UILabel()<br>        label.text = &quot;Hello UIKit&quot;<br>        return label<br>    }<br>    func updateUIView(_ uiView: UILabel,<br>                      context: Context) {<br>        uiView.textColor = .systemBlue<br>    }<br>}</pre><p>Now use it like a normal SwiftUI view.</p><pre>struct ContentView: View {<br>  var body: some View {<br>        CustomLabel()<br>    }<br>}</pre><p>SwiftUI doesn’t care that it’s UIKit underneath.</p><h4>Embedding UIViewController</h4><p>Some SDKs require an entire view controller instead of a simple view.</p><p>SwiftUI provides another protocol:</p><pre>UIViewControllerRepresentable</pre><p>Example:</p><pre>struct CameraView: UIViewControllerRepresentable {<br>  func makeUIViewController(context: Context)<br>        -&gt; UIImagePickerController {<br>        UIImagePickerController()<br>    }<br>    func updateUIViewController(<br>        _ uiViewController: UIImagePickerController,<br>        context: Context<br>    ) {<br>    }<br>}</pre><p>Now it behaves like any SwiftUI screen.</p><h4>When Should You Use Each?</h4><p>When Should You Use Each?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a79dd95037f22425e305a0b2d96b628/href">https://medium.com/media/4a79dd95037f22425e305a0b2d96b628/href</a></iframe><h4>Common Mistakes</h4><h4>1. Rewriting Everything</h4><p>A complete rewrite usually introduces unnecessary risk.</p><p>Migration should happen gradually.</p><h4>2. Mixing State Management</h4><p>Avoid managing the same piece of data in multiple places.</p><p>Use a single source of truth through ObservableObject, @StateObject, or your preferred architecture.</p><h4>3. Ignoring Lifecycle Differences</h4><p>UIKit has lifecycle methods like:</p><pre>viewDidLoad()<br>viewWillAppear()<br>viewDidDisappear()</pre><p>SwiftUI relies on:</p><pre>.onAppear()<br>.onDisappear()<br>.task()</pre><p>Understanding these differences helps prevent duplicate network requests and unexpected behavior.</p><h4>Real-World Example</h4><p>Imagine you’re maintaining a banking application that has existed for eight years.</p><p>The dashboard was built in UIKit.</p><p>The new investment feature is developed in SwiftUI.</p><p>Instead of rewriting the dashboard, you simply push the SwiftUI screen using UIHostingController.</p><p>Later, the investment screen requires a PDF viewer available only in UIKit.</p><p>You wrap it using UIViewRepresentable.</p><p>Both frameworks coexist without conflict.</p><p>This is how many production applications evolve: incrementally, pragmatically, and with minimal disruption.</p><h3>Key Takeaways</h3><ul><li>UIKit and SwiftUI are complementary, not competing.</li><li>Use UIHostingController to bring SwiftUI into UIKit.</li><li>Use UIViewRepresentable for UIKit views inside SwiftUI.</li><li>Use UIViewControllerRepresentable for UIKit view controllers.</li><li>Prefer incremental migration over complete rewrites.</li><li>Keep a single source of truth for your state.</li></ul><p>Mastering these bridges allows you to build modern iOS applications while preserving the stability of mature codebases. The strongest iOS engineers aren’t defined by the framework they prefer; they’re defined by their ability to choose the right tool for the problem and make different technologies work together elegantly.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32f80433b8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built My Third iOS App: Here’s What I Learned Building Profyl]]></title>
            <link>https://medium.com/@sachindrafernando3/i-built-my-third-ios-app-heres-what-i-learned-building-profyl-cd084b98c622?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd084b98c622</guid>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 21:36:18 GMT</pubDate>
            <atom:updated>2026-04-24T21:36:18.879Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A digital business card app built with SwiftUI and Firebase</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PS2KQtpGWGJZyzsvIl1fw.png" /></figure><p>Paper business cards are outdated. You hand them out at events, meetings, and conferences, and most of them end up in a drawer or a trash can. I wanted to solve that problem, so I built <strong>Profyl: </strong>a digital business card app that lives in your pocket.</p><p>This is my third iOS app on the App Store, and by far the most technically ambitious one.</p><p>⸻</p><h4><strong>The Problem</strong></h4><p>Networking in 2026 still relies heavily on exchanging contact information manually. You either swap phone numbers awkwardly, search for each other on LinkedIn, or hand over a paper card that gets lost within a week.</p><p>I wanted something simpler: one app where you can create a beautiful digital card, customize it for different situations, and share it instantly with a QR code.</p><p>⸻</p><h4><strong>What Profyl Does</strong></h4><p>Profyl lets you create multiple profile modes: <strong>Professional, Personal, Creative, Student, and Freelancer, </strong>each with its own theme color and layout. Heading to a job interview? Switch to Professional mode. Going to a social event? Flip to Personal.</p><p>Here’s what’s packed into the app:</p><p>• <strong>Multiple Profile Modes — </strong>one identity, multiple cards for different occasions</p><p>• <strong>QR Code Sharing</strong> — anyone can scan your code to view your profile instantly</p><p>• <strong>Social Links</strong> — aggregate all your social media, websites, and contact info in one place</p><p>• <strong>Custom Themes</strong> — personalize each mode with your choice of accent color</p><p>• <strong>Contact Book</strong> — save profiles of people you meet</p><p>• <strong>Analytics</strong> — track profile views, link clicks, and QR scans</p><p>• <strong>Cloud Sync</strong> — your data is stored securely with Firebase and syncs across devices</p><p>⸻</p><h4><strong>The Tech Stack</strong></h4><p>I went fully native with this one:</p><p>• <strong>SwiftUI</strong> — the entire UI is declarative, no UIKit wrappers</p><p>• <strong>Firebase Authentication</strong> — email/password sign-in with password reset</p><p>• <strong>Firebase Firestore</strong> — cloud storage for user profiles</p><p>• <strong>MVVM Architecture</strong> — clean separation with @​Observable view models and @​Main​Actor concurrency</p><p>• <strong>CoreImage</strong> — on-device QR code generation</p><p>• <strong>PhotosUI</strong> — native photo picker with automatic image compression</p><p>One decision I’m proud of: profile images are compressed to under 500KB using progressive JPEG quality reduction before being stored. This keeps Firestore costs low, and load times fast; the compression runs on a background thread so the UI never stutters.</p><p>Analytics are tracked locally using UserDefaults with an in-memory cache layer, so logging an event doesn’t trigger a disk read/write cycle every time. Small optimization, but it matters when the app scales.</p><p>⸻</p><h4><strong>Lessons From My Third App</strong></h4><p><strong>1. Start with the architecture</strong></p><p>With my first two apps, I dove straight into building views. This time, I set up the MVVM structure, service protocols, and constants file first. It made everything faster down the line. Adding a new feature meant plugging into an existing pattern instead of refactoring.</p><p><strong>2. Don’t over-engineer early, but clean up often</strong></p><p>I started with a local-only profile service, then swapped it for Firebase when the time was right. Because I coded against a protocol (Profile​Service​Protocol), the switch was seamless. But I also made sure to delete the unused local service before shipping; dead code is technical debt.</p><p><strong>3. The App Store review process teaches you things</strong></p><p>Apple’s review team will catch what you miss. Account deletion must actually delete all data. Demo credentials must actually work. Privacy policies must be hosted and accessible. These aren’t optional; they’re requirements that make your app better.</p><p><strong>4. Ship, then iterate</strong></p><p>Profyl isn’t “done.” I have plans for Sign in with Apple, NFC sharing, and more customization options. But the core experience is solid, and it’s in users’ hands now. That matters more than a perfect feature list.</p><p>⸻</p><h4><strong>What’s Next</strong></h4><p>I’m planning to add:</p><p>• Sign in with Apple for faster onboarding</p><p>• NFC tap-to-share for in-person networking</p><p>• More profile customization (fonts, layouts, backgrounds)</p><p>• Export contacts as vCards</p><p>⸻</p><h4><strong>Try It Out</strong></h4><p>Profyl is available now on the App Store:</p><p><a href="https://apps.apple.com/us/app/profyl/id6761790454">Download Profyl on the App Store <em>(link)</em></a></p><p>If you’re tired of paper business cards and want a smarter way to share your professional identity, give it a try. I’d love to hear your feedback.</p><p>⸻</p><p><em>Thanks for reading. If you’re an indie developer working on your own apps, I’d love to connect.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd084b98c622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Privacy-First Period Tracker with SwiftUI and SwiftData: Here’s How]]></title>
            <link>https://medium.com/@sachindrafernando3/i-built-a-privacy-first-period-tracker-with-swiftui-and-swiftdata-heres-how-95761dd14029?source=rss-f7169ed3b1dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/95761dd14029</guid>
            <dc:creator><![CDATA[Sachindra Fernando]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 00:35:28 GMT</pubDate>
            <atom:updated>2026-04-07T00:35:28.371Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A deep dive into building HerPulse: architecture decisions, cycle prediction algorithms, and why your health data should never leave your device.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKo7ufmbI3TkB7rBPO2ZCw.png" /></figure><p>Most period trackers on the App Store ask for an account. They sync to a server. They collect analytics. Some of them sell anonymized data to third parties. For an app that handles some of the most intimate health data a person can have, that never sat right with me.</p><p>So I built HerPulse. A period tracker that does everything on-device. No accounts. No servers. No analytics. No cloud sync. Just SwiftUI, SwiftData, and your iPhone.</p><p>This is the technical story of how I built it.</p><p>⸻</p><h4><strong>The Architecture</strong></h4><p>HerPulse follows a clean SwiftUI architecture with three distinct layers:</p><p><strong>Models — </strong>powered entirely by SwiftData. There are three core models: Cycle​Entry for period start and end dates, Daily​Log for flow intensity, mood, symptoms, and notes, and User​Settings for cycle defaults and preferences.</p><p><strong>Helpers</strong> — pure Swift logic with no UI dependencies. This is where the cycle calculator, symptom predictor, and PDF report generator live.</p><p><strong>Views</strong> — organized by feature. Calendar, Logging, Insights, Onboarding, and Settings each get their own directory.</p><p>The app entry point injects a shared App​State (an @​Observable class) via the environment, and a single Model​Container manages all persistence. There’s no networking layer. There’s no Combine. It’s intentionally minimal.</p><pre>@main<br>struct GirlyApp: App {<br>    @State private var appState = AppState()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environment(appState)<br>        }<br>        .modelContainer(for: [CycleEntry.self, DailyLog.self, UserSettings.self])<br>    }<br>}</pre><p>⸻</p><h4>Cycle Prediction: The Math Behind It</h4><p>The prediction engine lives in Cycle​Calculator and works in two stages.</p><p>Stage one calculates averages. Given a user’s logged cycle entries, the calculator sorts them chronologically, computes the gap between consecutive period start dates, and averages those gaps. If the user has fewer than two entries, it falls back to their manually configured cycle length.</p><p>Stage two predicts the next cycle. Using the average cycle length and the last period start date, it calculates:</p><p>• Next period start: last start + average cycle length<br>• Ovulation date: next period start − 14 days (the luteal phase is relatively constant)<br>• Fertile window: 5 days before ovulation through 1 day after</p><p>This is the calendar method — the same approach used in clinical settings as a baseline estimate. It’s simple, transparent, and honest about what it is: an estimate based on your personal data, not a guarantee.</p><pre>static func predict(<br>    lastPeriodStart: Date,<br>    cycleLength: Int,<br>    periodDuration: Int<br>) -&gt; CyclePrediction {<br>    let nextStart = lastPeriodStart.adding(days: cycleLength)<br>    let ovulationDay = nextStart.adding(days: -14)<br>    let fertileStart = ovulationDay.adding(days: -5)<br>    let fertileEnd = ovulationDay.adding(days: 1)<br>    // ...<br>}</pre><p>⸻</p><h4>Symptom Predictions That Learn From You</h4><p>This was the feature I was most excited to build.</p><p>Symptom​Predictor maps every logged symptom to its cycle day, not the calendar date, but which day of the menstrual cycle it occurred on. Over time, patterns emerge. If a user logs cramps on cycle day 25 across three different cycles, the app starts predicting cramps around day 25.</p><p>The algorithm:</p><p>1. For each daily log, determine which cycle it belongs to by finding the most recent cycle entry before that date.<br>2. Calculate the cycle day (days since that cycle’s start + 1).<br>3. Group symptoms by their average cycle day.<br>4. If a symptom’s predicted day is within 5 days of the current cycle day, surface it as an upcoming prediction with a likelihood score.</p><p>The likelihood is calculated as the frequency of that symptom across all logged cycles. If you logged headaches in 4 out of 6 tracked cycles, the likelihood is ~67%.</p><p>No machine learning models. No cloud processing. Just frequency analysis on local data.</p><p>⸻</p><h4>The Calendar: SwiftUI Performance at Scale</h4><p>The calendar was the trickiest UI challenge. It renders 25 months of data in a paged Tab​View, with each month displaying a Lazy​VGrid of day cells. Every cell needs to know its type: normal, period, predicted period, fertile, or ovulation, which means running the day-type calculation for every visible cell.</p><p>Each Day​Cell renders differently based on its type: gradient fills for period days, dashed borders for predictions, teal for fertile windows, gold for ovulation. The today indicator uses a secondary-colored ring overlay.</p><p>I used Lazy​VGrid intentionally here. Combined with the paged Tab​View, only the visible month renders its full grid. The other 24 months exist as lightweight placeholders until swiped into view.</p><p>⸻</p><h4>PDF Reports: UIKit Where It Makes Sense</h4><p>For the doctor report feature, I reached for UIGraphics​PDFRenderer. SwiftUI doesn’t have native PDF generation, and this is one of those cases where UIKit is still the right tool.</p><p>The generator pulls cycle history, symptom frequencies, and mood distribution, then renders a clean, formatted PDF with proper pagination. If a section would overflow the page, it starts a new one. The footer makes it clear: “This report is for informational purposes only and is not medical advice.”</p><p>This was a deliberate feature choice. People often forget their cycle details at doctor’s appointments. Having a shareable PDF summary removes that friction.</p><p>⸻</p><h4>Dark Mode: Adaptive Theming</h4><p>I centralized all colors in a Girly​Theme enum with adaptive colors using UIColor trait collections. Each color resolves differently based on the user’s appearance setting:</p><pre>static let background = Color(UIColor { traits in<br>    traits.userInterfaceStyle == .dark<br>        ? UIColor(red: 0.10, green: 0.08, blue: 0.14, alpha: 1)<br>        : UIColor(red: 0.99, green: 0.96, blue: 0.98, alpha: 1)<br>})</pre><p>Deep purple-black backgrounds in dark mode. Light pink-lavender in light mode. The accent colors — the hot pink primary, teal fertile indicators, gold ovulation markers — stay vibrant in both modes because they were chosen with sufficient contrast from the start.</p><p>Since every view in the app references Girly​Theme rather than hardcoding colors, a single file controls the entire visual identity.</p><p>⸻</p><h4>Privacy as Architecture</h4><p>The privacy model isn’t a feature bolted on at the end. It’s an architectural constraint that shaped every decision:</p><p>• SwiftData with no CloudKit sync — Data lives in the app sandbox. Period.<br>• No analytics SDK — No Firebase, no Mixpanel, no Amplitude. I have no idea how many users I have or what they do in the app.<br>• No network calls — There is literally no networking code in the project. The app works in airplane mode because that’s the only mode it has.<br>• Settings transparency — The settings screen has a privacy dashboard that explicitly states: on-device storage, no cloud sync, no analytics, no third-party sharing.</p><p>This wasn’t the easy path. I can’t do A/B testing. I can’t track retention. I can’t send push notifications about features. But I think the tradeoff is worth it for an app that handles menstrual health data.</p><p>⸻</p><h4>What I’d Do Differently</h4><p>SwiftData is still young. I hit a few rough edges with @​Query and complex predicates. For simple use cases like this, it works well. But if I needed relational queries or more sophisticated filtering, I might have reached for Core Data with a SwiftUI wrapper.</p><p>The prediction algorithm could be smarter. Weighted averages (giving more importance to recent cycles), outlier detection, and Bayesian updating would all improve accuracy. I kept it simple for v1 because transparent simplicity beats opaque complexity for health data.</p><p>HealthKit integration would let users import existing data and export to Apple Health, keeping everything in the Apple ecosystem. That’s on the roadmap.</p><p>⸻</p><h4>Shipping It</h4><p>HerPulse is built with SwiftUI, SwiftData, Swift Charts, and UIKit (for PDF generation). It targets iOS 17+. It does one thing, and it tries to do it well.</p><p>If you’re an iOS developer thinking about building a health app, my advice is this: start with the privacy model, not the feature list. The constraints will guide you to simpler, better decisions.</p><p>Your users’ health data deserves the same care you’d want for your own.</p><p>⸻</p><p>HerPulse is available on the App Store (<a href="https://apps.apple.com/us/app/herpulse/id6761367286">link</a>).</p><p>If you have questions about the implementation or want to discuss SwiftUI architecture, feel free to reach out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95761dd14029" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>