---
title: "How do you convert a String to an Int in Swift?"
description: "Use Int(string), which returns an optional, and unwrap it safely. Trim whitespace first and use a default or guard for invalid input."
url: "https://bugsee.com/answers/swift/convert-a-string-to-an-int/"
---

# How do you convert a String to an Int in Swift?

Use `Int(text)`. It returns an optional, because the text might not be a number, so unwrap it with `if let`, `guard let` or `??`.

```swift
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.

## Related questions

- [How do you fix "Unexpectedly found nil while unwrapping an Optional value"?](https://bugsee.com/answers/swift/unexpectedly-found-nil-while-unwrapping-optional/)
