<?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 Hansaanuradha on Medium]]></title>
        <description><![CDATA[Stories by Hansaanuradha on Medium]]></description>
        <link>https://medium.com/@hansaanuradha93?source=rss-48c45391f02d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FX3OpQqWd2gkiaql.jpg</url>
            <title>Stories by Hansaanuradha on Medium</title>
            <link>https://medium.com/@hansaanuradha93?source=rss-48c45391f02d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 08:26:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hansaanuradha93/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[Ponytail: The AI Coding Skill That Refuses to Over-Build]]></title>
            <link>https://medium.com/aeturnuminc/ponytail-the-ai-coding-skill-that-refuses-to-over-build-5f418644ff5c?source=rss-48c45391f02d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f418644ff5c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hansaanuradha]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 12:22:51 GMT</pubDate>
            <atom:updated>2026-10-09T06:35:14.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAkJ52eiRogrvzi9FKRjpg.png" /></figure><h4>The lazy senior dev, as a skill</h4><p>You’re familiar with that kind of person: they have a long ponytail, wear oval glasses, and have been with the company longer than the version control system. If you show them fifty lines of code, they’ll look at them, say nothing, and then substitute them with just one. Ponytail transfers that instinct into an AI coding agent — a capability that causes it to consider whether the code actually needs to exist before it writes a single line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*rEPkqvPDhhPQLXz10ocNuQ.png" /></figure><p>The mascot has oval glasses and has no patience when fifty lines are required when only one is needed. One request, two very different amounts of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHfQJA5nkiydArozOl99tg.png" /></figure><p>It’s the same model and the same request — the only difference is whether it resorts to using what is already available before referring to a library.How it thinks: seven checks before any code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxYq9RfSuEWqBlbyFwNXZw.png" /></figure><p>The first six steps usually arrive at a solution before the seventh step needs to construct anything new.</p><h3>Meet the competition</h3><p>Two further approaches are evaluated using Ponytail’s own benchmark. <strong>Caveman</strong> takes a different approach in that it leaves the code as it is and instead makes the agent’s responses more concise, along with introducing a local proxy which compresses the logs and the test output before the agent reads them again. A simpler baseline — simply instructing the model to <strong>follow YAGNI and to prefer one-liners</strong> in the prompt — is also tested, serving as a stand-in for the effect that a simple prompt adjustment can have without any installation.</p><p>Each of the three analyses involves the same twelve real coding tickets from the same repository, which means the comparison isn’t merely promotional material.</p><h3>Where it refuses to cut corners</h3><p>The ladder has no say in whether the code is safe — it only determines how much code is written.</p><p>Validation, error handling, security checks, and accessibility must be included at all times. The 120-line cache class must be insisted on, and it will then be built — slowly and correctly, while you are watching.</p><p>Lacking enthusiasm regarding the solution, but not lacking concern about the consequences. Getting it running</p><h3>Getting it running</h3><p>Same ladder, different install command depending on which agent you run:</p><p>Claude Code</p><pre>/plugin marketplace add DietrichGebert/ponytail<br><br>/plugin install ponytail@ponytail</pre><p>Codex</p><pre> codex plugin marketplace add DietrichGebert/ponytail &amp;&amp; codex plugin add ponytail@ponytail</pre><p>GitHub Copilot CLI</p><pre>copilot plugin marketplace add DietrichGebert/ponytail &amp;&amp; copilot plugin install ponytail@ponytail</pre><p>Gemini CLI</p><pre>gemini extensions install https://github.com/DietrichGebert/ponytail</pre><p>Cursor</p><pre> git clone https://github.com/DietrichGebert/ponytail then node ponytail/scripts/cursor-hooks.js install</pre><p>Grok Build</p><pre>grok plugin install DietrichGebert/ponytail --trust</pre><p>OpenClaw</p><pre>clawhub install ponytail</pre><p>Full install matrix, uninstall commands, and version notes live on the repo itself.</p><h3>What’s actually been measured on Caveman</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTLDPdKOUnEKLIzQOt6TqA.png" /></figure><p>The 65% figure that is marketed is not a single validated figure; the nearest independently verified figure, from JetBrains, is 8.5% from real agentic coding sessions.</p><h3>The numbers: three approaches, same benchmark</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjWAsfOyrXzh2PJxkyqGYQ.png" /></figure><p>The three figures are from Ponytail’s own benchmark repository; there is no independent third party involved in this comparison, so regard the exact percentages as a claim made by the vendor until you carry out the test yourself. It should be mentioned that the simple YAGNI prompt, although it was competitive in terms of cost and time, was the only one to fail the adversarial safety check (95% compared to 100% for the other two).</p><h3>Side by side</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5c3HIpRzUlzvYMUoAgHSw.png" /></figure><h3>The takeaway</h3><p>Ponytail and Caveman aren’t in fact rivals; rather, they operate at different levels. Caveman deals with what the agent reads and states, while Ponytail cuts down the code itself, since it is the code that actually determines review time and defect rate, not just the number of tokens. A simple YAGNI prompt manages to go a long way without cost, but it is the only one of the three that showed signs of problems with safety.</p><p>When making your choice, the question comes down to what you’re trying to optimize for: for sessions that involve a lot of reading, Caveman’s proxy is the better option, while for those that involve a lot of coding, Ponytail’s ladder is preferable — yet both groups of maintainers state that the two stacks do not conflict, so there is seldom a good reason to select just one.</p><h3>References</h3><ul><li><a href="https://github.com/DietrichGebert/ponytail">Ponytail on GitHub</a> — the skill, install matrix, and benchmark source</li><li><a href="https://github.com/JuliusBrussee/caveman">Caveman on GitHub</a> — the skill, proxy, and the comparison tables this piece draws on</li><li><a href="https://github.com/DietrichGebert/ponytail/blob/main/benchmarks/results/2026-06-18-agentic.md">Ponytail’s agentic benchmark write-up</a> — the LOC, token, cost and time numbers</li></ul><p>JetBrains’ and Adobe Research’s figures are as reported inside Caveman’s README; neither was independently re-verified here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f418644ff5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aeturnuminc/ponytail-the-ai-coding-skill-that-refuses-to-over-build-5f418644ff5c">Ponytail: The AI Coding Skill That Refuses to Over-Build</a> was originally published in <a href="https://medium.com/aeturnuminc">Aeturnum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Swift Code Formatting with Git Hooks and SwiftFormat]]></title>
            <link>https://medium.com/@hansaanuradha93/automating-swift-code-formatting-with-git-hooks-and-swiftformat-6a8b7de4ca06?source=rss-48c45391f02d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a8b7de4ca06</guid>
            <dc:creator><![CDATA[Hansaanuradha]]></dc:creator>
            <pubDate>Mon, 05 May 2025 12:52:05 GMT</pubDate>
            <atom:updated>2025-05-06T06:41:33.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyVryb23bgi7LZk5X0mJ2Q.png" /></figure><h3>Automating Swift Code Formatting with Git Hooks and SwiftFormat</h3><p>Maintaining consistent code style across your iOS project can be a challenge — especially when working in a team. Recently, I replaced SwiftLint&#39;s formatting responsibility with SwiftFormat, using a Git pre-commit hook to auto-format staged Swift files. Here’s a step-by-step guide to help you do the same.</p><h4>🧱 Why SwiftFormat Over SwiftLint?</h4><p>While SwiftLint is powerful for linting and style enforcement, it isn’t designed primarily for formatting. SwiftFormat is built specifically to format Swift code based on a defined set of rules. Offloading formatting to SwiftFormat simplifies our linting process and improves consistency.</p><h4>🪜 Step-by-Step Integration</h4><ol><li>Install SwiftFormat</li></ol><p>Make sure SwiftFormat is installed locally:</p><pre>brew install swiftformat</pre><p>You can confirm it’s installed with:</p><pre>which swiftformat</pre><p>If installed correctly, you’ll get something like:</p><pre>/opt/homebrew/bin/swiftformat</pre><p>2. Create a SwiftFormat Config File</p><p>In your project root, create a file named .swiftformat:</p><pre>touch .swiftformat</pre><p>Populate it with the rules you want. You can reference their official documentation to choose rules for your use case,</p><p><a href="https://github.com/nicklockwood/SwiftFormat/blob/main/Rules.md#markTypes">https://github.com/nicklockwood/SwiftFormat/blob/main/Rules.md#markTypes</a></p><p>Here’s an example we used:</p><pre># Files to exclude from formatting<br>--exclude Pods,**/.build,**/Package.swift,vendor/bundle,scripts,fastlane,**/L10n.swift,**/Assets.swift,**/*.generated.swift,**/Generated,xcode-productivity/**/*.swift,**/Carthage/**/*.swift<br><br># Indentation and braces<br>--allman false             # Use K&amp;R style braces (not Allman)<br>--indent 4                 # Use 4 spaces for indentation<br>--xcodeindentation enabled # Match Xcode&#39;s indentation style<br><br># Header handling<br>--header ignore            # Preserve existing file headers<br><br># Self usage<br>--self init-only           # Only use &#39;self.&#39; when required in initializers<br><br># Wrapping behavior<br>--wraparguments before-first     # Place first argument after function name, others on new lines<br>--wrapparameters before-first    # Place first parameter after function name, others on new lines<br>--wrapcollections before-first   # Place first element after opening bracket, others on new lines<br>--wrapreturntype if-multiline    # Place return arrow and type on a new line if the function declaration spans multiple lines<br>--wrapconditions before-first    # Place first condition after if/guard/while, others on new lines<br><br># Attribute placement<br>--funcattributes prev-line  # Place function attributes on the line before the function<br>--typeattributes prev-line  # Place type attributes on the line before the type declaration<br>--varattributes same-line   # Place variable attributes on the same line as the variable<br><br># Mark comments - Fix for the line break issue<br>--marktypes always          # Always add MARK comments for types<br>--beforemarks               # Add blank line before each mark<br>--lineaftermarks false      # No blank line after marks<br>--markextensions always     # Mark Extentions<br>--extensionmark<br><br># Organization<br>--organizetypes class,enum,struct,extension # Order of top-level declarations<br>--enumnamespaces always    # Use enum namespaces except for lower case names<br><br># Disabled rules<br>--disable preferKeyPath        # Don&#39;t automatically convert to keyPath syntax<br>--disable initCoderUnavailable # Don&#39;t add NSCoding unavailability<br>--disable redundantRawValues   # Don&#39;t remove explicit raw values that match enum case names<br>--disable redundantReturn      # Allow explicit returns to improve readability where desired<br>--disable redundantSelf        # Handled by self init-only option above<br><br># Enabled rules<br>--enable markTypes             # Enable MARK comments formatting<br>--enable blankLinesBetweenImports # Add blank line after imports section<br>--enable sortedImports         # Sort import statements alphabetically<br>--enable consecutiveSpaces     # Remove multiple consecutive spaces<br>--enable duplicateImports      # Remove duplicate import statements<br>--enable isEmpty               # Use isEmpty instead of count checks</pre><p>3. Add a Git Pre-Commit Hook</p><p>[Optional] If you have not initiate a git repository yet, you can initiate it like below. If you already have a git repository, you can ingore this step.</p><pre>git init</pre><p>Create a pre-commit hook script that runs swiftformat before every commit:</p><pre>touch .git/hooks/pre-commit</pre><p>Inside your project’s .git/hooks/ directory, create or edit the pre-commit hook script:</p><pre>nano .git/hooks/pre-commit</pre><p>Paste in the following shell script:</p><pre>#!/bin/sh<br><br>RED=&quot;\e[31m&quot;<br>GREEN=&quot;\e[32m&quot;<br>MAGENTA=&quot;\e[35m&quot;<br>YELLOW=&quot;\e[33m&quot;<br>ENDCOLOR=&quot;\e[0m&quot;<br><br>set -e<br>set -u<br>set -o pipefail<br><br>script_name=$(basename $BASH_SOURCE)<br>files_to_format=$(mktemp)<br><br>function cleanup() {<br>  rm -f files_to_format<br>  exit 0<br>}<br><br>trap cleanup 0 1 2 EXIT<br><br># Add /opt/homebrew/bin to PATH if necessary<br>if test -d &quot;/opt/homebrew/bin/&quot;; then<br>    PATH=&quot;/opt/homebrew/bin/:${PATH}&quot;<br>fi<br>export PATH<br><br># 1. Get git root directory and locate config<br>git_root_directory=$(git rev-parse --show-toplevel)<br>config=&quot;${git_root_directory}/.swiftformat&quot;<br><br># 2. Get staged Swift files<br>staged_swift_files=$(git diff --diff-filter=d --staged --name-only | grep -e &#39;\(.*\).swift$&#39;)<br><br># If no staged Swift files, exit early<br>if [ -z &quot;$staged_swift_files&quot; ]<br>then<br>  printf &quot;🟣${MAGENTA} $script_name: No Swift file to format \n.${ENDCOLOR}&quot;<br>  printf &quot;\n&quot;<br>  exit 0<br>fi<br><br>printf &quot;%s\n&quot; &quot;${staged_swift_files[@]}&quot; &gt; files_to_format<br><br># 3. Run SwiftFormat using mint (or you can use the installed version directly)<br>if command -v mint &gt;/dev/null 2&gt;&amp;1; then<br>  mint run swiftformat --quiet --config &quot;$config&quot; --filelist files_to_format --exclude Pods,**/.build,**/Package.swift,vendor/bundle,scripts,fastlane,**/L10n.swift,**/Assets.swift,**/*.generated.swift,**/Generated,xcode-productivity/**/*.swift,**/Carthage/**/*.swift<br>  formatting_result=$?<br>else<br>  # Fallback if mint is not found<br>  if command -v swiftformat &gt;/dev/null 2&gt;&amp;1; then<br>    swiftformat --quiet --config &quot;$config&quot; --filelist files_to_format --exclude Pods,**/.build,**/Package.swift,vendor/bundle,scripts,fastlane,**/L10n.swift,**/Assets.swift,**/*.generated.swift,**/Generated,xcode-productivity/**/*.swift,**/Carthage/**/*.swift<br>    formatting_result=$?<br>  else<br>    printf &quot;🔴${RED} $script_name: swiftformat is not installed. Please install it to format your code.${ENDCOLOR}\n&quot;<br>    exit 1<br>  fi<br>fi<br><br># 4. Re-add formatted files to staging<br>git add $staged_swift_files<br><br># 5. Output results<br>if [ $formatting_result -eq 0 ]; then<br>    printf &quot;🟢${GREEN} $script_name: The following files have been formatted with SwiftFormat:\n${ENDCOLOR}&quot;<br>    printf &quot;${MAGENTA}$(cat files_to_format)${ENDCOLOR}\n&quot;<br>else<br>    printf &quot;🔴${RED} $script_name: swiftformat failed ${ENDCOLOR}&quot;<br>fi<br><br>exit $formatting_result</pre><p>Then make the hook executable:</p><pre>chmod +x .git/hooks/pre-commit</pre><p>4. Test the Hook</p><p>Try committing a Swift file with misaligned formatting. If all is set up correctly:</p><ul><li>The hook will auto-format it using SwiftFormat.</li><li>The formatted file will be automatically re-added to the commit.</li><li>You won’t need to worry about formatting during code reviews again.</li></ul><h4>✅ Outcome</h4><p>Now every commit automatically formats Swift code according to your rules — no manual intervention required. This significantly reduces style-related churn in PRs and keeps the codebase consistent.</p><h4>💬 Final Thoughts</h4><p>This setup is lightweight, fast, and requires no IDE plugin. It works regardless of the editor or environment you’re using, as long as you’re committing via Git.</p><p>If you’re looking to enforce consistent Swift code style across your team, I highly recommend this approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a8b7de4ca06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from XCTest to Swift Testing: An Advanced Guide]]></title>
            <link>https://medium.com/@hansaanuradha93/migrating-from-xctest-to-swift-testing-an-advanced-guide-bcedba8f2375?source=rss-48c45391f02d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcedba8f2375</guid>
            <dc:creator><![CDATA[Hansaanuradha]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 15:38:18 GMT</pubDate>
            <atom:updated>2025-04-06T15:39:37.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_nYAeRT15sPKsZyyS_yNA.png" /></figure><p>Swift Testing is on of the latest Apple frameworks released with Xcode 15 which brings declarative approach to writing tests. For experienced iOS developers with established XCTest suites, migrating to Swift Testing opens substantial opportunities but comes with its own set of challenges.</p><p>This article focuses on migration process from XCTest to Swift Testing while discussing on advanced techniques and solutions to common problems. Let’s discuss not just the “how” but also “why” behind each and every migration step.</p><h3>Understanding the Fundamental Differences</h3><p>Let’s dive into the code, let’s explore the core differences between these frameworks,</p><h4>XCTest (Traditional Approach)</h4><ul><li>Class based inheritance model (XCTestCase)</li><li>Method naming conventions (test methods must start with “test”)</li><li>Setup/teardown methods (setUp, tearDown)</li><li>Assertion functions (XCTAssert, XCTAssertEqual, etc.)</li></ul><h4>Swift Testing (Modern Approach)</h4><ul><li>Macro based test declarations (@Test)</li><li>Function based testing model</li><li>Test discovery through type metadata</li><li>Advanced test parameterisation</li><li>Built-in async/await support</li><li>More expressive assertion messages</li></ul><h3>Migration Process</h3><p>Let’s dive into the migration process now.</p><h4>Migration Step 1: Project Setup</h4><p>Let’s import and replace the XTTest with Swift Testing package.</p><pre>import Testing<br>@testable import MyApp</pre><h4>Migration Step 2: Converting Test Structure</h4><p>Let’s migrate a basic XCTest class.</p><pre>import XCTest<br>@testable import MyApp<br><br>class UserValidatorTests: XCTestCase {<br>    var validator: UserValidator!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        validator = UserValidator()<br>    }<br>    <br>    override func tearDown() {<br>        validator = nil<br>        super.tearDown()<br>    }<br>    <br>    func testValidateEmail_WithValidEmail_ReturnsTrue() {<br>        // Given<br>        let email = &quot;user@example.com&quot;<br>        <br>        // When<br>        let result = validator.validateEmail(email)<br>        <br>        // Then<br>        XCTAssertTrue(result)<br>    }<br>    <br>    func testValidateEmail_WithInvalidEmail_ReturnsFalse() {<br>        // Given<br>        let email = &quot;invalid-email&quot;<br>        <br>        // When<br>        let result = validator.validateEmail(email)<br>        <br>        // Then<br>        XCTAssertFalse(result)<br>    }<br>}</pre><p>Now, let’s rewrite this using Swift Testing.</p><pre>import Testing<br>@testable import MyApp<br><br>struct UserValidatorTests {<br>    @Test<br>    func validateEmail_withValidEmail_returnsTrue() throws {<br>        // Given<br>        let validator = UserValidator()<br>        let email = &quot;user@example.com&quot;<br>        <br>        // When<br>        let result = validator.validateEmail(email)<br>        <br>        // Then<br>        #expect(result == true)<br>    }<br>    <br>    @Test<br>    func validateEmail_withInvalidEmail_returnsFalse() throws {<br>        // Given<br>        let validator = UserValidator()<br>        let email = &quot;invalid-email&quot;<br>        <br>        // When<br>        let result = validator.validateEmail(email)<br>        <br>        // Then<br>        #expect(result == false)<br>    }<br>}</pre><p><strong>Key differences:</strong></p><ol><li>No inheritance needed. Use a struct instead of a class extending XCTestCase</li><li>Tests are marked with @Test macro instead of method naming conventions</li><li>#expect macros replace XCTAssert functions</li><li>Each test is self-contained so no shared state via instance properties</li></ol><h4>Migration Step 3: Advanced Assertions</h4><p>We can map the old XCTest functions to Swift Testing macros as follows,</p><pre>// XCTest assertions<br>XCTAssertEqual(a, b)<br>XCTAssertNotEqual(a, b)<br>XCTAssertTrue(expression)<br>XCTAssertFalse(expression)<br>XCTAssertNil(expression)<br>XCTAssertNotNil(expression)<br>XCTAssertThrowsError(expression)<br><br>// Swift Testing equivalents<br>#expect(a == b)<br>#expect(a != b)<br>#expect(expression)<br>#expect(!expression)<br>#expect(expression == nil)<br>#expect(expression != nil)<br>#expect(throws: error, try expression)</pre><p>Swift Testing comes out of the box with more descriptive assertion failures.</p><pre>// Old way<br>XCTAssertEqual(user.name, &quot;John&quot;, &quot;User name should be John&quot;)<br><br>// New way - message is automatically generated<br>#expect(user.name == &quot;John&quot;)<br>// Ex: Failure message: Expected user.name (which is &quot;Mark&quot;) to be equal to &quot;John&quot;</pre><h4>Migration Step 4: Setup and Teardown</h4><p>XCTest utilizes <strong>setUp</strong> and <strong>tearDown</strong> methods to manage test lifecycle while Swift Testing uses a different approach.</p><pre>// Old XCTest way<br>class NetworkTests: XCTestCase {<br>    var mockServer: MockServer!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        mockServer = MockServer.start()<br>    }<br>    <br>    override func tearDown() {<br>        mockServer.stop()<br>        mockServer = nil<br>        super.tearDown()<br>    }<br>    <br>    func testNetworkRequest() {<br>        // Test using mockServer<br>    }<br>}<br><br>// New Swift Testing way<br>struct NetworkTests {<br>    @Test<br>    func networkRequest() throws {<br>        // Using Swift&#39;s defer for teardown<br>        let mockServer = MockServer.start()<br>        defer { mockServer.stop() }<br>        <br>        // Test using mockServer<br>    }<br>    <br>    // For shared setup across multiple tests<br>    func createMockServer() -&gt; MockServer {<br>        return MockServer.start()<br>    }<br>}</pre><p>For more complex setUp / tearDown scenarios, we can utilize test utility functions or Swift’s built-in resource management.</p><h4>Migration Step 5: Parameterized Tests</h4><p>XCTest requires separate test method or loops for parameterized test while Swift Testing offers an elegant way.</p><pre>// Old XCTest way<br>class CalculatorTests: XCTestCase {<br>    func testAddition() {<br>        let testCases = [<br>            (a: 1, b: 2, expected: 3),<br>            (a: -1, b: 1, expected: 0),<br>            (a: 10, b: 20, expected: 30)<br>        ]<br>        <br>        for testCase in testCases {<br>            let result = Calculator.add(testCase.a, testCase.b)<br>            XCTAssertEqual(result, testCase.expected)<br>        }<br>    }<br>}<br><br>// New Swift Testing way<br>struct CalculatorTests {<br>    @Test(.parameterized([<br>        (a: 1, b: 2, expected: 3),<br>        (a: -1, b: 1, expected: 0),<br>        (a: 10, b: 20, expected: 30)<br>    ]))<br>    func addition(a: Int, b: Int, expected: Int) throws {<br>        let result = Calculator.add(a, b)<br>        #expect(result == expected)<br>    }<br>}</pre><p>This approach provides cleaner code and also a clearer failure messages, showing exactly which parameter combination failed.</p><h4>Migration Step 6: Async Testing</h4><p>Swift Testing provides support for async / await testing out of the box.</p><pre>// Old XCTest way<br>class UserServiceTests: XCTestCase {<br>    func testFetchUser() {<br>        let expectation = XCTestExpectation(description: &quot;Fetch user&quot;)<br>        <br>        let service = UserService()<br>        service.fetchUser(id: &quot;123&quot;) { result in<br>            switch result {<br>            case .success(let user):<br>                XCTAssertEqual(user.id, &quot;123&quot;)<br>            case .failure(let error):<br>                XCTFail(&quot;Failed with error: \(error)&quot;)<br>            }<br>            expectation.fulfill()<br>        }<br>        <br>        wait(for: [expectation], timeout: 5.0)<br>    }<br>}<br><br>// New Swift Testing way<br>struct UserServiceTests {<br>    @Test<br>    func fetchUser() async throws {<br>        let service = UserService()<br>        let user = try await service.fetchUser(id: &quot;123&quot;)<br>        #expect(user.id == &quot;123&quot;)<br>    }<br>}</pre><p>Swift Testing does not need exceptions and timeouts since it uses the modern way of async / await APIs.</p><h4>Migration Step 7: Test Discovery and Organization</h4><p>XCTests utilizes class inheritance and method naming conventions to discover test cases. However, Swift Testing utilizes type metadata.</p><pre>// Old way: All tests must be in methods starting with &quot;test&quot;<br>class FeaturesTests: XCTestCase {<br>    func testFeatureA() { /* ... */ }<br>    func testFeatureB() { /* ... */ }<br>    func helperMethod() { /* Not a test */ }<br>}<br><br>// New way: Tests are explicitly marked with @Test<br>struct FeatureTests {<br>    @Test func featureA() { /* ... */ }<br>    @Test func featureB() { /* ... */ }<br>    func helperMethod() { /* Not a test */ }<br>}</pre><p>And Swift Testing supports test suites and hierarchies.</p><pre>struct AppTests {<br>    @Suite struct NetworkTests {<br>        @Test func apiConnection() { /* ... */ }<br>        @Test func dataDecoding() { /* ... */ }<br>    }<br>    <br>    @Suite struct StorageTests {<br>        @Test func dataPersistence() { /* ... */ }<br>    }<br>}</pre><h3>Common Migration Challenges</h3><h4>Challenge 1: Shared Test State</h4><p><strong>Problem</strong>: XCTest shares state via instance properties while Swift Testing prefers isolated tests.</p><p><strong>Solution</strong>: Consider if shared state is actually necessary. If it is, use function parameters, or factory methods.</p><pre>// Instead of shared state:<br>struct DatabaseTests {<br>    func createTestDatabase() -&gt; Database {<br>        let db = Database(inMemory: true)<br>        db.migrate()<br>        return db<br>    }<br>    <br>    @Test<br>    func insertRecord() throws {<br>        let db = createTestDatabase()<br>        // Test with db<br>    }<br>    <br>    @Test<br>    func queryRecord() throws {<br>        let db = createTestDatabase()<br>        // Test with db<br>    }<br>}</pre><h4>Challenge 2: Mocking and Dependencies</h4><p><strong>Problem</strong>: XCTest often uses instance properties for mocks however, Swift Testing tests need to be self-contained.</p><p><strong>Solution</strong>: Use dependency injection or factory functions.</p><pre>struct PaymentServiceTests {<br>    func createService(with mockNetwork: NetworkProtocol = MockNetwork()) -&gt; PaymentService {<br>        return PaymentService(network: mockNetwork)<br>    }<br>    <br>    @Test<br>    func processPayment() throws {<br>        let mockNetwork = MockNetwork()<br>        mockNetwork.stubResponse(for: &quot;payment&quot;, with: successResponse)<br>        <br>        let service = createService(with: mockNetwork)<br>        let result = service.processPayment(amount: 100)<br>        <br>        #expect(result.success)<br>    }<br>}</pre><h4>Challenge 3: Handling XCTest-Specific APIs</h4><p><strong>Problem:</strong> Some XCTest features like measuring performance don’t have direct Swift Testing equivalents.</p><p><strong>Solution:</strong> Create custom measurement utilities or utilize Swift’s built-in timing functions.Challenge 3: Handling XCTest-Specific APIs</p><pre>// Old XCTest way<br>func testSortPerformance() {<br>    measure {<br>        _ = largeArray.sorted()<br>    }<br>}<br><br>// New Swift Testing way<br>@Test<br>func sortPerformance() throws {<br>    let startTime = DispatchTime.now()<br>    _ = largeArray.sorted()<br>    let endTime = DispatchTime.now()<br>    <br>    let nanoseconds = endTime.uptimeNanoseconds - startTime.uptimeNanoseconds<br>    let milliseconds = Double(nanoseconds) / 1_000_000<br>    <br>    // Expected to complete in under 100ms<br>    #expect(milliseconds &lt; 100) <br>}</pre><h4>Challenge 4: Test Ordering Dependencies</h4><p><strong>Problem:</strong> Some XCTest suites rely on test execution order even though Swift Testing tests should be independent.</p><p><strong>Solution:</strong> Refactor tests to be independent or explicitly manage dependencies.</p><pre>struct DatabaseTests {<br>    @Test<br>    func createAndQueryDatabase() throws {<br>        let db = Database(inMemory: true)<br>        db.migrate()<br>        <br>        // Create test data<br>        try db.insert(user: User(id: 1, name: &quot;Test&quot;))<br>        <br>        // Query in the same test<br>        let result = try db.query(User.self, id: 1)<br>        #expect(result?.name == &quot;Test&quot;)<br>    }<br>}</pre><h3>When Not to Migrate (Yet)</h3><p>Even though Swift Testing comes with lots of features, some scenarios might warrant stating with XCTest temporarily.</p><ol><li>Project with extensive UI testing suing SCUITest since Swift Testing is currently focused on unit testing.</li><li>Some third party libraries may still not fully support Swift Testing.</li><li>Projects with complex custom XCTest extensions that would be difficult to recreate.</li></ol><h3>Conclusion</h3><p>Migrating from XCTest to Swift Testing does not only involve syntax changes but also a shift in testing philosophy from an inheritance based model to a modern, declarative approach. This modern approach comes with numerous benefits.</p><ul><li>More expressive test declarations</li><li>Better failure messages</li><li>First-class support for modern Swift features</li><li>Cleaner test organization</li><li>Improved test isolation</li></ul><p>While the migration process might uncover architectural issues in your test suite, this often enables more reliable and maintainable tests. By migration into this modern approach, you’re not just updating your testing framework but also you’re investing in a more robust testing strategy for your Swift projects.</p><h3>Resources</h3><ul><li><a href="https://developer.apple.com/documentation/testing/migratingfromxctest">Apple’s Official Migration Guide</a></li><li><a href="https://developer.apple.com/documentation/testing">Swift Testing Documentation</a></li><li><a href="https://github.com/apple/swift-testing">Swift Testing GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcedba8f2375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup a New iOS Widget which shares the same Core Data database as your iOS app]]></title>
            <link>https://medium.com/aeturnuminc/setup-a-new-widget-which-shares-the-same-core-data-database-as-your-ios-app-c72eb5134e23?source=rss-48c45391f02d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c72eb5134e23</guid>
            <dc:creator><![CDATA[Hansaanuradha]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 16:55:17 GMT</pubDate>
            <atom:updated>2023-05-30T10:10:52.358Z</atom:updated>
            <content:encoded><![CDATA[<p>You have an existing iOS app that uses Core Data and now you want to add a new iOS widget extension to your app which shares the same Core Data as your iOS app. Let&#39;s find out how we can do that.</p><p>In order for our widget extension and our app to share the persisted data, they have to be in an App Group. Here is the Apple documentation for App Groups. <a href="https://developer.apple.com/documentation/xcode/configuring-app-groups">https://developer.apple.com/documentation/xcode/configuring-app-groups</a></p><p>In simple terms, an App Group allows multiple apps developed by the same team to access a shared container. So the container is the key there. Right now the data in our app is in a container that is attached to our app which means only our app can see the data, not our widget extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPVgpGpFL_YtVZQ7H2kNMg.jpeg" /></figure><p>When we built this app container, there will be this <strong>Shared Container</strong>, to which our app and the widget extension will have access. The key here is a new container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5JYh_9ozxvg6VZcIH31jw.jpeg" /></figure><p>That means our existing data in our app is in a different container which is the old container. That is the reason why we have to do the migration from the <strong>old container to the new shared container</strong>. Let&#39;s make this in a few steps.</p><p><strong>Step 1</strong>: Create the widget extension.</p><p><strong>Go to “File” → “Target” → Go to ”Filter” → Type in “Widget” → Click on “Widget Extension” → “Next” → Give your widget extension a name → Hit “Finish” → Click on “Activate”</strong></p><p>Now we have our widget extension.</p><p><strong>Step 2:</strong> Create the App Group.</p><p><strong>Click on “Project Name” → Click on App Target → Click on “Signing &amp; Capabilities” → Click on “+ Capability” → Search “App Groups” in the window → Click on “App Groups”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOJVRlNuwt5xiyDo8qlOJA.png" /></figure><p>Now you will see “App Groups” in your capabilities section.</p><p><strong>Copy the Bundle Identifier → Click on “+” icon → Paste the Bundle Identifier right after “group.” → Click on “Ok”</strong></p><p>App Groups name should be like <strong>“groups.{app bundle identifier}”</strong></p><p>Ex: “group.com.castleCode.Calendar”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFKCMv6KQTdmHwuPerfVpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FicYUch9maGwNuJZpKe-0Q.png" /></figure><p>Now our app is in the App Group which we created after the name <strong>“group.com.castleCode.Calendar”</strong>.</p><p>Now let&#39;s add our widget extension to the same App Group.</p><p><strong>Click on “Widget Extension Name” → Click on “Signing &amp; Capabilities” → Click on “+ Capability” → Search “App Groups” in the window → Click on “App Groups” → Click on the check box (right left to the App Group name)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JY6t4t3lFZh8fgvlUrjuFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_1Igw37cC42OH0kVr_vFg.png" /></figure><p>Now we have added both our app and the widget extension to the App Group we newly created.</p><p><strong>Step 3:</strong> Migrate from the Old container to the new Shared Container.</p><p>For that, we need a URL for the old container and another URL for the shared container.</p><p>Add this to the <strong>PersistenceController.swift</strong> file.</p><pre>// To find the database name, check out the screenshot below.<br>let datebaseName = &quot;Calendar.sqlite&quot;<br><br>var oldStoreURL: URL {<br>  let directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!<br>  return directory.appendingPathComponent(datebaseName)<br>}<br>    <br>var sharedStoreURL: URL {<br>  // Change the identifier to your App Group name<br>  let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: &quot;group.com.castleCode.Calendar&quot;)!<br>  return container.appendingPathComponent(datebaseName)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a79dtPuf88hgGollg45NVQ.png" /></figure><p>Now we are gonna create the new <strong>Shared Container</strong> which will be shared by both our app and widget extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5JYh_9ozxvg6VZcIH31jw.jpeg" /></figure><p>Let&#39;s point our app to the Shared Container now. In order to do that, Change the <strong>init(inMemory: Bool = false)</strong> in <strong>PersistenceController.swift</strong> file.</p><pre>init(inMemory: Bool = false) {<br>  container = NSPersistentContainer(name: &quot;Calendar&quot;)<br>        <br>  if inMemory {<br>    container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: &quot;/dev/null&quot;)<br>  } else if !FileManager.default.fileExists(atPath: oldStoreURL.path) {<br>    // Point our app to the new Shared Container<br>    container.persistentStoreDescriptions.first!.url = sharedStoreURL<br>  }<br>                <br>  container.loadPersistentStores(completionHandler: { (storeDescription, error) in<br>    if let error = error as NSError? {<br>      fatalError(&quot;❌ Unresolved error \(error), \(error.userInfo)&quot;)<br>    }<br>  })<br>                <br>  container.viewContext.automaticallyMergesChangesFromParent = true<br>}</pre><p>Now if we run the app, we will see that our app does not have any data that was previously saved, since it is now pointing to a new Shared Container. We can’t see any selected dates in the app now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vy_keNXrM7ZEGhFyDwk30w.jpeg" /></figure><p>Now we need to migrate the data from our <strong>Old Container to the Shared Container</strong>. Let&#39;s write a function for that which will be in the <strong>PersistenceController.swift</strong> file.</p><pre>private func migrateStore(for container: NSPersistentContainer) {<br>        <br>  print(&quot;➡️ went into migrate stores&quot;)<br>        <br>  let coordinator = container.persistentStoreCoordinator<br>        <br>  guard let oldStore = coordinator.persistentStore(for: oldStoreURL) else {<br>    print(&quot;🎅🏻 old store no longer exists&quot;)<br>    return<br>  }<br>        <br>  print(&quot;🏪 old store is stil there&quot;)<br>        <br>  do {<br>    let _ = try coordinator.migratePersistentStore(oldStore, to: sharedStoreURL, type: .sqlite)<br>    print(&quot;✈️ migrated to shared store from old store&quot;)<br>  } catch {<br>    fatalError(&quot;❌ Unable to migrate to shared store&quot;)<br>  }<br>        <br>  do {<br>    try FileManager.default.removeItem(at: oldStoreURL)<br>    print(&quot;🚮 deleted old store&quot;)<br>  } catch {<br>    print(&quot;❌ Unable to delete the old store&quot;)<br>  }<br>}</pre><p>Let&#39;s see what we are doing in that function line by line,</p><p>In order to migrate from one container to another, we need a coordinator which is a type of NSPersistentContainer. Let&#39;s create it,</p><pre> let coordinator = container.persistentStoreCoordinator</pre><p>What we are gonna do after this migration is we are gonna delete the <strong>Old Container</strong> since we don’t need it anymore. So let&#39;s check whether we have the old container in the first place.</p><pre>guard let oldStore = coordinator.persistentStore(for: oldStoreURL) else {<br>  print(&quot;🎅🏻 old store no longer exists&quot;)<br>  return<br>}</pre><p>If the compiler passes this guard statement means we have an Old Container. If not, that means we don’t have an Old Container which also means we don’t have to do the migration.</p><p>The next bit of code actually the migration itself. Let&#39;s see how the migration is done from the <strong>Old Container to the Shared Container</strong>.</p><pre>do {<br>  let _ = try coordinator.migratePersistentStore(oldStore, to: sharedStoreURL, type: .sqlite)<br>  print(&quot;✈️ migrated to shared store from old store&quot;)  <br>} catch {<br>  fatalError(&quot;❌ Unable to migrate to shared store&quot;)<br>}</pre><p>That’s really it for the migration. Now we can get rid of the <strong>Old Container</strong> which we don’t need anymore.</p><pre>do {<br>  try FileManager.default.removeItem(at: oldStoreURL)<br>  print(&quot;🚮 deleted old store&quot;)<br>} catch {<br>  print(&quot;❌ Unable to delete the old store&quot;)<br>}</pre><p>Finally, we migrated from the <strong>Old Container to the new Shared Container</strong> and deleted the Old Container.</p><p>Now let&#39;s call this function <strong>“migrateStore(for container: NSPersistentContainer)”</strong> in <strong>PersistenceController.swift. </strong>Right after calling this function, this is how the PersistenceController should look like.</p><pre>import CoreData<br><br>struct PersistenceController {<br>    static let shared = PersistenceController()<br>    let datebaseName = &quot;Calendar.sqlite&quot;<br>    <br>    var oldStoreURL: URL {<br>        let directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!<br>        return directory.appendingPathComponent(datebaseName)<br>    }<br>    <br>    var sharedStoreURL: URL {<br>        let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: &quot;group.com.castleCode.Calendar&quot;)!<br>        return container.appendingPathComponent(datebaseName)<br>    }<br><br>    static var preview: PersistenceController = {<br>        let result = PersistenceController(inMemory: true)<br>        let viewContext = result.container.viewContext<br>        <br>        let startDate = Calendar.current.dateInterval(of: .month, for: .now)!.start<br>        <br>        for dayOffset in 0..&lt;30 {<br>            let newDay = Day(context: viewContext)<br>            newDay.date = Calendar.current.date(byAdding: .day, value: dayOffset, to: startDate)<br>            newDay.didStudy = Bool.random()<br>        }<br>        <br>        do {<br>            try viewContext.save()<br>        } catch {<br>            let nsError = error as NSError<br>            fatalError(&quot;❌ Unresolved error \(nsError), \(nsError.userInfo)&quot;)<br>        }<br>        <br>        return result<br>    }()<br><br>    let container: NSPersistentContainer<br><br>    init(inMemory: Bool = false) {<br>        container = NSPersistentContainer(name: &quot;Calendar&quot;)<br>        <br>        if inMemory {<br>            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: &quot;/dev/null&quot;)<br>        } else if !FileManager.default.fileExists(atPath: oldStoreURL.path) {<br>            print(&quot;👴🏻 old store doesn&#39;t exist. Using new shared URL&quot;)<br>            container.persistentStoreDescriptions.first!.url = sharedStoreURL<br>        }<br>        <br>        print(&quot;🧑‍💻 container URL: \(container.persistentStoreDescriptions.first!.url!)&quot;)<br>        <br>        container.loadPersistentStores(completionHandler: { (storeDescription, error) in<br>            if let error = error as NSError? {<br>                fatalError(&quot;❌ Unresolved error \(error), \(error.userInfo)&quot;)<br>            }<br>        })<br>        <br>        migrateStore(for: container)<br>        <br>        container.viewContext.automaticallyMergesChangesFromParent = true<br>    }<br>    <br>    private func migrateStore(for container: NSPersistentContainer) {<br>        <br>        print(&quot;➡️ went into migrate stores&quot;)<br>        <br>        let coordinator = container.persistentStoreCoordinator<br>        <br>        guard let oldStore = coordinator.persistentStore(for: oldStoreURL) else {<br>            print(&quot;🎅🏻 old store no longer exists&quot;)<br>            return<br>        }<br>        <br>        print(&quot;🏪 old store is stil there&quot;)<br>        <br>        do {<br>            let _ = try coordinator.migratePersistentStore(oldStore, to: sharedStoreURL, type: .sqlite)<br>            print(&quot;✈️ migrated to shared store from old store&quot;)<br>        } catch {<br>            fatalError(&quot;❌ Unable to migrate to shared store&quot;)<br>        }<br>        <br>        do {<br>            try FileManager.default.removeItem(at: oldStoreURL)<br>            print(&quot;🚮 deleted old store&quot;)<br>        } catch {<br>            print(&quot;❌ Unable to delete the old store&quot;)<br>        }<br>    }<br>}</pre><p>If we run the app now, it will successfully do the migration from the old container to the shared container. Before all of this, we had a container that our app can only see. Now we have migrated to a shared container, both our app and widget extension can see. Now we can see both our app and the widget have the same exact data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RzresiPgz-6Isy1TiiFlfw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c72eb5134e23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aeturnuminc/setup-a-new-widget-which-shares-the-same-core-data-database-as-your-ios-app-c72eb5134e23">Setup a New iOS Widget which shares the same Core Data database as your iOS app</a> was originally published in <a href="https://medium.com/aeturnuminc">Aeturnum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>