Why Use Swift?
Sprout could, in theory, be written in many languages. So why do almost all new iPhone apps choose Swift? The answer is not fashion. Swift was designed to remove whole families of bugs, and to do it without making your code slower.
The rule
Swift trades a little ceremony for safety, speed and clarity.
The "little ceremony" is that Swift makes you be precise: say whether a value can change, say whether it might be missing, give things the right type. In return you get three things.
- Safety. A value must be set before it is used. A value that might be missing (an optional) must be checked before you touch it. Reading past the end of a list stops the program cleanly instead of reading random memory.
- Speed. Swift compiles to native machine code, so it runs at roughly the speed of the lower-level languages it replaced.
- Clarity. Code reads close to English, with labels on arguments:
let streak = 4
markDone(habit: "Read", on: today)Swift also has modern tools built in: async/await for waiting on slow work like the network, and checks that catch two parts of a program changing the same data at once.
And there is a practical reason: SwiftUI and most new Apple frameworks are built for Swift first. If you want the newest features on iPhone, Mac, Apple Watch or Vision Pro, Swift is where they arrive.
The shortcut
For each rule Swift makes you follow, ask: which bug does this rule prevent? The rule is the price; the missing bug is what you bought.
The rule: say if a value can change
You write
letfor a habit name that never changes. Prize: no other code can accidentally rename it.
When a Swift rule feels fussy, run this check. Nearly always, the fussiness is a crash or a silent wrong answer that never reaches your users.
Drills
Answer fast — trust the rule.
Swift refuses to let you use a possibly-missing value until you check it. Which benefit is that?
Why does Swift code usually run fast?
Sprout's team wants the newest SwiftUI features on Apple Watch. What does that suggest?
Which pair best describes Swift's deal with you?
Remember
- Swift trades a little ceremony for safety, speed and clarity.
- For each rule, ask which bug it prevents.
- New Apple frameworks, SwiftUI included, arrive in Swift first.
