Skip to content
AgileLogics
4 min read

Type Conversion

Prerequisites: Unwrapping optionals safely

Swift never converts between types automatically. You convert explicitly by creating a value of the new type from the old one.

Between number types

let whole = 7
let decimal = 2.9

print(Double(whole))
print(Int(decimal))
print(Int(decimal.rounded()))
7.0
2
3

Converting a Double to an Int truncates — it drops the decimal part. Round first if you want the nearest number.

Numbers to strings

let score = 42
let text = String(score)
print(text + "!")
print("\(score)!")
42!
42!

Strings to numbers

Converting text to a number can fail, so it returns an optional:

let inputs = ["42", "3.5", "abc", " 7"]

for input in inputs {
    if let number = Int(input) {
        print("\(input) → \(number)")
    } else {
        print("\(input) → not a whole number")
    }
}
42 → 42
3.5 → not a whole number
abc → not a whole number
 7 → not a whole number

Int(_:) is strict — even a leading space makes it fail. Trim input first (see Working with Strings). Double("3.5") handles decimals.

Common mistakes

  • Forgetting that Int("42") is an Int?, not an Int. Unwrap it with if let, guard let, or ??.