Use Int(text). It returns an optional, because the text might not be a number, so unwrap it with if let, guard let or ??.
let a = Int("42") // Optional(42)
let b = Int("4 2") // nil
let c = Int(" 42 ") // nil: whitespace is not accepted
let input = " 42 "
if let n = Int(input.trimmingCharacters(in: .whitespaces)) {
print(n + 1) // 43
}
let age = Int(input) ?? 0 // fall back to a default
let d = Double("3.5") // Optional(3.5)Avoid Int(text)! on user input, because any bad value crashes the app. For user-facing numbers in other locales, use NumberFormatter or the parsing APIs for FormatStyle so decimal separators are handled correctly.
