Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in Swift Using AI

Use an AI assistant inside Xcode to write Swift, run it, and prove it with XCTest. Swift is Apple's language for iPhone, iPad and Mac apps.

In short: you need a Mac and Xcode. Use GitHub Copilot for Xcode and/or ChatGPT in Xcode Intelligence. Give the formula, one example answer, ask for XCTest, and run the tests yourself.

Why Swift with AI

WHY

Almost every new iPhone app is written in Swift. UIKit and SwiftUI need a lot of repeated layout and state code. AI speeds that up. Money and math still need tests.

What you need (honest limits)

WHAT
  • A Mac: Xcode does not run on Windows or Linux. Without a Mac, practice Swift syntax in a cloud IDE, but you cannot build a real iOS app for the App Store.
  • Xcode: from the Mac App Store. Keep it updated.
  • GitHub Copilot for Xcode: a separate Mac app + Xcode Source Editor extension (Homebrew: brew install --cask github-copilot-for-xcode). Completions, chat and agent mode.
  • ChatGPT in Xcode: Xcode → Settings → Intelligence → turn on ChatGPT. Uses your ChatGPT account.
  • Apple's own coding intelligence: also in Xcode Intelligence settings (where your Xcode version offers it). Features change with Xcode releases — check Settings → Intelligence on your Mac.

How it flows

1 · Mac + Xcode create a project 2 · Enable Copilot / ChatGPT Intelligence / extension 3 · Clear prompt formula + example 4 · AI writes Swift read every line 5 · XCTest + Run all pass = keep

Install Copilot for Xcode

HOW
  1. On your Mac: brew install --cask github-copilot-for-xcode (or download the app from GitHub's Copilot for Xcode releases).
  2. Open the Copilot for Xcode app. Allow Accessibility and enable the Xcode Source Editor extension in System Settings → Extensions.
  3. Sign in with your GitHub account (device code flow).
  4. Open Xcode. Confirm Editor → GitHub Copilot appears.
  5. Optional: Xcode → Settings → Intelligence → turn on ChatGPT and sign in if you use that path too.

Step 1 — the prompt

COPY THIS PROMPT

Write a Swift function emi(principal: Double, annualRatePercent: Double, months: Int) -> Int for a loan EMI using EMI = P × r × (1+r)^n / ((1+r)^n − 1), where r is the monthly rate. Round to the nearest rupee. Zero interest means principal / months. Use precondition for bad input. Example: emi(principal: 500000, annualRatePercent: 9.0, months: 60) = 10379. Only return the code.

Step 2 — the code

Emi.swift
import Foundation

/// Monthly EMI in whole rupees. Zero interest → principal / months.
func emi(principal: Double, annualRatePercent: Double, months: Int) -> Int {
    precondition(principal > 0, "principal must be positive")
    precondition(months > 0, "months must be positive")
    precondition(annualRatePercent >= 0, "rate cannot be negative")

    if annualRatePercent == 0 {
        return Int((principal / Double(months)).rounded())
    }
    let r = annualRatePercent / 12.0 / 100.0
    let factor = pow(1.0 + r, Double(months))
    let value = principal * r * factor / (factor - 1.0)
    return Int(value.rounded())
}

#if DEBUG
assert(emi(principal: 500_000, annualRatePercent: 9.0, months: 60) == 10_379)
assert(emi(principal: 120_000, annualRatePercent: 0.0, months: 12) == 10_000)
#endif
We use the same EMI numbers as the Kotlin lesson so you can compare languages. On a Mac, put this in a Swift package or app target and run it. (This Linux draft box cannot run Xcode.)

Step 3 — XCTest

FOLLOW-UP PROMPT

Write XCTest cases for emi: 5 lakh at 9% for 60 months, and zero interest on 1.2 lakh over 12 months.

EmiTests.swift
import XCTest

// Put Emi.swift in the same app/test target, or import your module name.
final class EmiTests: XCTestCase {
    func testNinePercentSixtyMonths() {
        XCTAssertEqual(emi(principal: 500_000, annualRatePercent: 9.0, months: 60), 10_379)
    }
    func testZeroInterest() {
        XCTAssertEqual(emi(principal: 120_000, annualRatePercent: 0.0, months: 12), 10_000)
    }
    func testPositivePrincipalRequired() {
        // In a Debug build, a negative principal trips precondition and fails the test —
        // that is what we want. Prefer a throwing API in production code.
    }
}
# In Xcode: Product → Test (Cmd+U)
# Expect: testNinePercentSixtyMonths pass
# Expect: testZeroInterest pass

Settings and config

  1. Project rules: keep a short note in the repo (“Swift 5/6, SwiftUI, no force unwraps, XCTest for logic”).
  2. Prefer guard and if let over ! force unwraps when you accept AI code.
  3. For UI, say “SwiftUI” or “UIKit” in the prompt so the AI does not mix them.

Watch out (common AI mistakes in Swift)

  • Force unwrap ! — crashes on nil; ask for safe unwraps.
  • Wrong SDK or old APIs — say your iOS deployment target (e.g. iOS 17+).
  • Mixing UIKit and SwiftUI in one answer — pick one.
  • Assuming Windows works — real iOS builds need a Mac and Xcode.
  • Blind agent edits in Xcode — still read the diff; agent mode can change many files.
Rule: do not paste App Store Connect API keys, provisioning profiles or customer device data into any chat.

Try this yourself: ask AI for a Swift shelf code, then prove the cases

Hello friends. The live chapter already walked through a loan EMI helper in Swift with XCTest. This practice is a different fictional bookstore called Maple Quay Books. You ask an AI for a Swift function shelfCode that builds aisle and bay codes like A12-B03, rejects aisle or bay values outside 1 through 99 with a message containing 1 and 99, and proves the padding. On this drafting Linux machine there is no swiftc, so we did not compile Swift and XCTest was not run. We proved the same cases with a tiny Python behavioral twin under pytest: the starter twin failed 7 tests and passed 1, and the fixed twin passed all 8.

Ravindra Bagale's Tip

Put the exact format A12-B03 with two-digit zero padding and the rejection substring 1 and 99 in your prompt. Keep the XCTest file for your Mac even when you first prove the same cases with the Python twin.

Practice label: Maple Quay Books, every aisle and every bay code here is fictional teaching data. It is not a real bookstore. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box had no swiftc, and none was installed. XCTest was not run. The same shelf codes were proved with a Python twin under Python 3.13.5 and pytest 9.1.1. Starter twin: 7 failed, 1 passed. Fixed twin: 8 passed. The ShelfCodeTests.swift file is still the student-facing Swift test source.

Your task: start from the buggy ShelfCode.swift that prints unpadded codes and skips validation. Ask an AI to return A{aisle:02}-B{bay:02} for aisle and bay in 1...99, throw with a message containing 1 and 99 outside that range, and keep the XCTest file for your machine. On machines without Swift yet, you may also use the Python twin.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Optional twin setup: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Extra for Swift on your machine: open the files in Xcode or use swiftc with XCTest, confirm the toolchain version, and run ShelfCodeTests.swift. This drafting box did not have swiftc and did not install one.

Starter ShelfCode.swift (wrong padding, skips validation):

ShelfCode.swift
// Maple Quay Books shelf code helper (fictional teaching bookstore — not a real shop).
// Starter: builds a code for some aisles but wrong padding and no validation.
import Foundation

enum ShelfCodeError: Error, LocalizedError {
    case outOfRange(String)
    var errorDescription: String? {
        switch self {
        case .outOfRange(let message): return message
        }
    }
}

/// Build a shelf code like A12-B03 from aisle and bay numbers.
func shelfCode(_ aisle: Int, _ bay: Int) throws -> String {
    // Starter bugs: no range check; no zero-fill (A1-B3 instead of A01-B03).
    return "A\(aisle)-B\(bay)"
}

Simple tests ShelfCodeTests.swift (for your machine):

ShelfCodeTests.swift
import XCTest
@testable import MapleQuay

final class ShelfCodeTests: XCTestCase {
    func testAisleOneBayThree() throws {
        XCTAssertEqual(try shelfCode(1, 3), "A01-B03")
    }
    func testAisleTwelveBayNine() throws {
        XCTAssertEqual(try shelfCode(12, 9), "A12-B09")
    }
    func testAisleNinetyNineBayNinetyNine() throws {
        XCTAssertEqual(try shelfCode(99, 99), "A99-B99")
    }
    func testAisleFiveBayFortyTwo() throws {
        XCTAssertEqual(try shelfCode(5, 42), "A05-B42")
    }
    func testRejectsAisleZero() {
        XCTAssertThrowsError(try shelfCode(0, 5)) { error in
            XCTAssertTrue(String(describing: error).contains("1 and 99"))
        }
    }
    func testRejectsBayOneHundred() {
        XCTAssertThrowsError(try shelfCode(5, 100)) { error in
            XCTAssertTrue(String(describing: error).contains("1 and 99"))
        }
    }
    func testRejectsNegativeBay() {
        XCTAssertThrowsError(try shelfCode(10, -1)) { error in
            XCTAssertTrue(String(describing: error).contains("1 and 99"))
        }
    }
    func testRejectsAisleOneHundred() {
        XCTAssertThrowsError(try shelfCode(100, 1)) { error in
            XCTAssertTrue(String(describing: error).contains("1 and 99"))
        }
    }
}

Python twin starter (optional local proof without Swift):

shelf_code.py
"""Behavioral twin of Maple Quay Books shelfCode (starter — buggy padding)."""


def shelf_code(aisle: int, bay: int) -> str:
    if not isinstance(aisle, int) or isinstance(aisle, bool):
        raise TypeError("aisle must be an int")
    if not isinstance(bay, int) or isinstance(bay, bool):
        raise TypeError("bay must be an int")
    # Starter bugs: no range check; no zero-padding (A1-B3 instead of A01-B03).
    return f"A{aisle}-B{bay}"

Suggested AI ask (copy and adapt):

swift-prompt.txt
Write a Swift function func shelfCode(_ aisle: Int, _ bay: Int) throws -> String for fictional Maple Quay Books. Return A{aisle zero-padded to 2}-B{bay zero-padded to 2} when both aisle and bay are integers from 1 through 99 inclusive. Throw an error whose message contains 1 and 99 when either value is outside that range. Add XCTest cases covering padded codes and four rejection cases.

HOW to finish

HOW
  1. Save the starter Swift file and the test file in one project.
  2. Ask your AI assistant to add zero padding and validation with the 1 and 99 substring the tests search for.
  3. On a machine with Swift compile and run the tests. On this drafting box we used the Python twin instead: starter showed 7 failed and 1 passed.
  4. Run again after the fix. Expect 8 passed on the twin (or the matching XCTest count on your machine).

Real pytest twin output after the fixed twin:

pytest-after.txt
........                                                                 [100%]
8 passed in 0.01s
Optional completed ShelfCode.swift (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if the XCTest cases (or the Python twin) all pass.

ShelfCode.swift
import Foundation

enum ShelfCodeError: Error, LocalizedError {
    case outOfRange(String)
    var errorDescription: String? {
        switch self {
        case .outOfRange(let message): return message
        }
    }
}

func shelfCode(_ aisle: Int, _ bay: Int) throws -> String {
    if aisle < 1 || aisle > 99 || bay < 1 || bay > 99 {
        throw ShelfCodeError.outOfRange("aisle and bay must be between 1 and 99")
    }
    let a = String(format: "%02d", aisle)
    let b = String(format: "%02d", bay)
    return "A\(a)-B\(b)"
}

Troubleshooting

HOW
  1. Problem: shelfCode(1, 3) returns A1-B3. Fix: zero-pad both numbers to two digits so the result is A01-B03.
  2. Problem: shelfCode(0, 5) returns a code instead of an error. Fix: reject every aisle or bay outside 1...99 and put the substring 1 and 99 in the message.
  3. Problem: shelfCode(12, 9) returns A12-B9. Fix: bay 9 must become B09.
  4. Error: swiftc is missing on the drafting box. Fix: use the Python twin here, or open the Swift files in Xcode on your own machine without changing this server.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name the padding in the prompt

Ask for A12-B03 style codes with two-digit zero padding.
Run the tests and read which padded cases still fail.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep the rejection substring stable

Tests search for 1 and 99 inside the error text.
Ask the AI to keep those words even if it rewrites the sentence.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये padding सांगा

A12-B03 शैली आणि दोन अंक zero padding मागा.
Tests चालवा आणि अजून fail होणारे padded cases वाचा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Rejection substring स्थिर ठेवा

Tests error text मध्ये 1 and 99 शोधतात.
AI वाक्य बदलले तरीही ती शब्द ठेवायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. Can you build a real iPhone app with Xcode on Windows?

No. You need a Mac and Xcode.

2. What is emi(500000, 9%, 60 months) in our example?

10379 rupees.

3. Name two real AI options inside Xcode.

GitHub Copilot for Xcode, and ChatGPT via Xcode Intelligence.

4. Which Xcode command runs unit tests?

Product → Test (Cmd+U).

Save tokens and money

SMART AI USE

Give the formula in the prompt so the model does not guess. Ask for one function + tests. For UI work, send one screen at a time, not the whole storyboard dump.

Save these cards

INTERVIEW CARDAI Coding

How do you use AI for Swift?

Mac + Xcode; Copilot for Xcode and/or ChatGPT in Intelligence.
Clear prompt with example; prove with XCTest (Cmd+U).
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Copilot for Xcode vs ChatGPT in Xcode

Copilot for Xcode: GitHub app + editor extension; completions, chat, agent.
ChatGPT in Xcode: built into Intelligence settings with a ChatGPT account.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Swift with AI in 3

Needs a Mac.
Formula + example → EMI function.
XCTest with Cmd+U.
Ravindra Bagale · ravindrabagale.com/ai-coding