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
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)
- 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
Install Copilot for Xcode
- On your Mac:
brew install --cask github-copilot-for-xcode(or download the app from GitHub's Copilot for Xcode releases). - Open the Copilot for Xcode app. Allow Accessibility and enable the Xcode Source Editor extension in System Settings → Extensions.
- Sign in with your GitHub account (device code flow).
- Open Xcode. Confirm Editor → GitHub Copilot appears.
- Optional: Xcode → Settings → Intelligence → turn on ChatGPT and sign in if you use that path too.
Step 1 — the 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.swiftimport 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)
#endifStep 3 — XCTest
Write XCTest cases for emi: 5 lakh at 9% for 60 months, and zero interest on 1.2 lakh over 12 months.
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 passSettings and config
- Project rules: keep a short note in the repo (“Swift 5/6, SwiftUI, no force unwraps, XCTest for logic”).
- Prefer
guardandif letover!force unwraps when you accept AI code. - 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.
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.
नमस्कार मित्रांनो. Live chapter मध्ये Swift loan EMI helper आणि XCTest आधीच आले आहेत. हा सराव Maple Quay Books नावाच्या वेगळ्या काल्पनिक पुस्तकांच्या दुकानावर आहे. तुम्ही AI कडून shelfCode हा Swift function मागता जो A12-B03 सारखे aisle आणि bay कोड बनवतो, 1 ते 99 बाहेरच्या मूल्यांना 1 and 99 असलेल्या संदेशासह नाकारतो, आणि padding सिद्ध करतो. या drafting Linux मशीनवर swiftc नाही, म्हणून आम्ही Swift compile केले नाही आणि XCTest चालवले नाही. समान cases छोट्या Python behavioral twin ने pytest खाली सिद्ध केले: starter twin मध्ये 7 fail आणि 1 pass, आणि fixed twin मध्ये सर्व 8 पास.
नमस्ते दोस्तों. Live chapter में Swift loan EMI helper और XCTest पहले आ चुके हैं. यह अभ्यास Maple Quay Books नाम की अलग काल्पनिक किताबों की दुकान पर है. आप AI से shelfCode नाम का Swift function मांगते हो जो A12-B03 जैसे aisle और bay कोड बनाता है, 1 से 99 के बाहर मानों को 1 and 99 वाले संदेश के साथ अस्वीकार करता है, और padding साबित करता है. इस drafting Linux मशीन पर swiftc नहीं है, इसलिए हमने Swift compile नहीं किया और XCTest नहीं चलाया. वही cases छोटे Python behavioral twin से pytest के तहत साबित किए: starter twin में 7 fail और 1 pass, और fixed twin में सभी 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.
Ravindra Bagale's Tip – मराठी
Prompt मध्ये exact format A12-B03 (दोन अंक zero padding) आणि rejection substring 1 and 99 लिहा. Python twin ने आधी सिद्ध केले तरीही तुमच्या Mac साठी XCTest file जपून ठेवा.
Ravindra Bagale's Tip – हिंदी
Prompt में exact format A12-B03 (दो अंक zero padding) और rejection substring 1 and 99 लिखो. Python twin से पहले साबित करने पर भी अपने Mac के लिए XCTest file बचाए रखो।
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
- Create a project folder and open a terminal inside it.
- Optional twin setup: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - 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):
// 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):
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.txtWrite 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
- Save the starter Swift file and the test file in one project.
- Ask your AI assistant to add zero padding and validation with the 1 and 99 substring the tests search for.
- 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.
- 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.swiftimport 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
- Problem:
shelfCode(1, 3)returnsA1-B3. Fix: zero-pad both numbers to two digits so the result isA01-B03. - Problem:
shelfCode(0, 5)returns a code instead of an error. Fix: reject every aisle or bay outside 1...99 and put the substring1 and 99in the message. - Problem:
shelfCode(12, 9)returnsA12-B9. Fix: bay 9 must becomeB09. - 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.
Name the padding in the prompt
Keep the rejection substring stable
Prompt मध्ये padding सांगा
Rejection substring स्थिर ठेवा
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
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.