#24: Convert String to Int in Swift

Int has a failable initializer that parses numeric strings and returns an optional:

let good = Int("123")   // Optional(123)
let bad = Int("12a")    // nil

Because parsing can fail, unwrap the result safely:

if let number = Int(input) {
    print(number * 2)
} else {
    print("Not a valid integer")
}

This is preferable to force-unwrapping because user input, API payloads, and text fields are all unreliable sources.


I'm also on Twitter and GitHub.

Subscribe via RSS.