Type Safety and Type Casting
Sprout adds reading minutes (a Double) to a count of bonus minutes (an Int) and the code will not compile. Coming from a language that converts quietly, this feels strict. It is the whole point: Swift makes every conversion visible, so none of them happens by accident.
The rule
Swift never converts for you: wrap the value in the type you want.
Type safety means a value of one type cannot be used where another is expected. Even between two number types:
let bonus = 5 // Int
let minutesRead = 12.5 // Double
let total = minutesRead + bonus // error
let fixed = minutesRead + Double(bonus) // 17.5To convert, call the target type with the value. This is how numbers change type:
Double(5) // 5.0
Int(12.9) // 12 (the fraction is cut off, not rounded)
String(4) // "4"
Int("42") // 42, but as an optional: Int?
Int("forty") // nilTurning text into a number can fail, so Int("...") gives back an optional, a value that might be missing. The next lesson shows how to open it safely.
One exception: plain literals have no fixed type until they are used, so let t = 12.5 + 5 is fine and gives 17.5. Only named values of different types refuse to mix.
For values whose exact type is not known in advance, Swift has casting operators: is checks a type, as? tries to treat a value as a type and gives nil if it cannot.
let item: Any = 3
item is Int // true
item as? String // nilThe shortcut
At every place two values meet, ask "same type?" If not, pick the type the answer should have and wrap the odd one out: Double(x), Int(x), String(x). For Int(text), expect an optional back.
The values
minutesReadisDouble12.5.bonusisInt5.
The trap is expecting Int(12.9) to round. It cuts off the fraction and gives 12. Use .rounded() first when you want 13.
Drills
Answer fast — trust the rule.
With let a = 5 and let b = 2.5, which line compiles?
What is Int(9.99)?
What type is Int("12")?
Why does let t = 12.5 + 5 compile when adding a Double variable to an Int variable does not?
Remember
- Swift never converts for you: wrap the value in the type you want.
- At every meeting point, ask "same type?" and wrap the odd one out.
Int(x)cuts off fractions;Int(text)returns an optional.
