Why conversion is explicit
Swift never changes a value's type behind your back. An Int and a Double cannot be added, and a String cannot be joined to a number. When you need a different type, you create a new value of that type with an initialiser such as String(x), Int(x) or Double(x). The original is not touched.
The common conversions
| Goal | Code | Result |
|---|---|---|
| number to text | String(42) | "42" |
| Double to Int | Int(70.8) | 70 |
| text to Int | Int("100") | Optional(100) |
| text to Double | Double("9.5") | Optional(9.5) |
| Int to Double | Double(25) | 25.0 |
Number to string
String(score) builds the text form of a number, so String(42) is "42" and String(9.99) is "9.99". Use it before joining a number to text with +. Interpolation, "\(score)", does the same job inside a longer string.
Double to Int truncates
Int(price) with price = 9.99 gives 9. The decimal part is dropped, not rounded: the conversion truncates toward zero, so Int(3.99) is 3 and Int(-3.99) is -3.
Int to Double
Double(age) turns 25 into 25.0. You need it whenever an Int meets a Double in arithmetic: with age = 25 and price = 9.99, age * price does not compile, but Double(age) * price is 249.75. It also gives a fractional result for division, since Double(age) / 2 is 12.5 while age / 2 is 12.
String to number can fail
Not every string is a number. Int("2024") works, but Int("abc"), Int("9.5") and Int(" 5") have no valid result. Swift models this with an optional: Int(year) returns an Int?, which holds either the number or nil.
print(Int("2024") as Any, Int("abc") as Any, Int("9.5") as Any)
print(Double("9.5") as Any)
Optional(2024) nil nil
Optional(9.5)
To get the plain number you must unwrap the optional. Three ways, from the lesson's quick one to the safest:
Int(year)!force-unwraps. It is correct only when you are certain the text is a number. Onnilthe program crashes.Int(year) ?? 0supplies a default when the conversion fails.if let n = Int(text) { ... }runs a block only when the conversion succeeds.
let bad = "abc"
if let n = Int(bad) {
print(n)
} else {
print("not a number")
}
print(Int("x") ?? 0)
not a number
0
What the optional looks like
If you store Int(year) without unwrapping, the constant has the type Int?. Printing it shows the wrapper, Optional(2024), and arithmetic is rejected:
let year = "2024"
let yearInteger = Int(year)
print(yearInteger + 1)
error: value of optional type 'Int?' must be unwrapped to a value of type 'Int'
That error is the reason the lesson ends the line with !. With it, Int(year)! + 1 is 2025.
The exercise, step by step
The starter code gives three constants: age (an Int, 25), price (a Double, 9.99) and year (a String, "2024"). Below them, add three more.
ageString: the text form ofage, built withString(age). Its value is"25".priceInteger: the integer form ofprice, built withInt(price). Its value is9, because the decimals are dropped.yearInteger: the integer form ofyear, built withInt(year)!. Parsing returns an optional, and the!unwraps it. It is safe here because"2024"is a valid number. Its value is2024.
The solution in Swift
let age = 25
let price = 9.99
let year = "2024"
let ageString = String(age)
let priceInteger = Int(price)
let yearInteger = Int(year)!
After these lines, ageString is a String, and priceInteger and yearInteger are Ints. The constants age, price and year keep their original types and values.
More Swift details
- Converting to
Doublefor division.age / 2is integer division, butDouble(age) / 2is12.5. - Exact conversion.
Int(exactly: 3.5)isnil, whileInt(exactly: 3.0)isOptional(3). - Bases.
Int("ff", radix: 16)parses hexadecimal and givesOptional(255).
Common mistakes
- Expecting rounding.
Int(9.99)is9, not10. - Forgetting the
!or another unwrap. Without it,yearIntegerwould be anInt?, and arithmetic on it would not compile. - Force-unwrapping text you did not check. User input should go through
if letor??. - Mixing types in arithmetic.
age * pricedoes not compile. WriteDouble(age) * price, which is249.75.
Key takeaways
- Conversions create new values with
String(...),Int(...)andDouble(...). Int(someDouble)truncates toward zero.- Converting text to a number returns an optional; unwrap it with
!only when it cannot fail.
