Swift – Convert String to Int
To convert a numeric String to an integer in Swift, pass the string to the Int initializer. The conversion returns an optional Int? because the string may not contain a valid integer.
The basic syntax to convert a String value x to an integer is:
Int(x)
For example, Int("256") returns Optional(256), while Int("256 abc") returns nil. The entire string must represent a valid integer in the expected format.
Why Swift Int(String) Returns an Optional Integer
String-to-integer conversion can fail at runtime. A string may contain letters, decimal points, spaces, an unsupported number format, or a value outside the range supported by Int. Swift represents this possible failure by returning Int? instead of a guaranteed Int.
Int() returns an Optional Integer value, and we can convert this to an Integer value using Optional Value Unwrapping !, as shown in the following.
var result = Int(str)
if result != nil {
let x = result! //unwrap to Int
//code
}
The code above checks for nil before force-unwrapping. In new Swift code, optional binding with if let or guard let is generally clearer because it avoids a separate nil check and the explicit ! operator.
Convert a Valid Numeric String to Int in Swift
In this example, we take a String value in str and convert this value to Integer.
main.swift
var str = "256"
var result = Int(str)
if result != nil {
let x = result! //unwrap to Int
print(x)
}
Output

The string contains only valid integer characters, so Int(str) produces an optional containing 256. After the nil check, the optional is unwrapped and printed.
Handle an Invalid String-to-Int Conversion in Swift
If the value in String cannot be converted to an Integer, Int() returns nil value. In that case, check if the value returned by Int() is not nil. Only if not nil, proceed with unwrapping the returned optional value.
main.swift
var str = "256 abc"
var result = Int(str)
if result != nil {
let x = result! //unwrap to Int
print(x)
} else {
print("Result of Int() is nil.")
}
Output

The conversion fails because "256 abc" is not a complete integer representation. Swift does not extract the numeric prefix automatically; it returns nil.
Safely Convert String to Int with if let
Optional binding with if let converts and unwraps the integer in one statement. The success block runs only when the conversion produces a value.
let text = "420"
if let number = Int(text) {
print("Integer value: \(number)")
} else {
print("The string is not a valid integer.")
}
Output
Integer value: 420
Inside the first branch, number has the non-optional type Int. No force-unwrapping is needed.
Convert String to Int with guard let in a Swift Function
Use guard let when the rest of a function requires a valid integer. Invalid input is handled early, and the unwrapped value remains available after the guard statement.
func printDouble(of text: String) {
guard let number = Int(text) else {
print("Invalid integer: \(text)")
return
}
print(number * 2)
}
printDouble(of: "25")
printDouble(of: "twenty-five")
Output
50
Invalid integer: twenty-five
Use a Default Integer When Swift Conversion Fails
The nil-coalescing operator ?? supplies a fallback value when Int() returns nil.
let text = "unknown"
let number = Int(text) ?? 0
print(number)
Output
0
Use a fallback only when the default value has a clear meaning in the application. Otherwise, handling the failure explicitly helps distinguish invalid input from a genuine value such as zero.
Convert Signed and Whitespace-Padded Strings to Int
The Int initializer accepts an optional leading plus or minus sign. However, surrounding whitespace should be removed before conversion when input comes from a text field, file, or external source.
let positive = Int("+18")
let negative = Int("-42")
let input = " 75\n"
let trimmedInput = input.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedNumber = Int(trimmedInput)
print(positive ?? 0)
print(negative ?? 0)
print(trimmedNumber ?? 0)
Output
18
-42
75
Trimming removes only the characters at the beginning and end of the string. It does not make mixed content such as "75 items" a valid integer.
Convert Binary, Octal, and Hexadecimal Strings to Int
Use Int(_:radix:) when the string represents a number in a base other than decimal. Common radix values are 2 for binary, 8 for octal, and 16 for hexadecimal.
let binary = Int("1010", radix: 2)
let octal = Int("17", radix: 8)
let hexadecimal = Int("FF", radix: 16)
print(binary ?? 0)
print(octal ?? 0)
print(hexadecimal ?? 0)
Output
10
15
255
The digits must be valid for the selected radix. For example, Int("102", radix: 2) returns nil because binary numbers can contain only 0 and 1.
Why Decimal Strings Cannot Be Converted Directly to Int
A value such as "12.75" is not an integer string, so Int("12.75") returns nil. Parse it as a Double first when decimal input is expected, and then decide how the fractional part should be handled.
let text = "12.75"
if let decimal = Double(text) {
let truncated = Int(decimal)
print(truncated)
}
Output
12
Converting a finite Double to Int removes the fractional portion toward zero. This is different from rounding. Apply an explicit rounding rule first when the application requires the nearest integer, floor, or ceiling.
Prevent the “Optional Int Must Be Unwrapped” Error
The expression Int(text) has the type Int?. Passing it directly to code that requires Int produces an error similar to “value of optional type ‘Int?’ must be unwrapped to a value of type ‘Int’.”
Unwrap the result with optional binding, guard let, a switch over the optional, or a suitable fallback value:
let text = "32"
if let number = Int(text) {
let doubled = number * 2
print(doubled)
}
Avoid using Int(text)! unless the string is guaranteed to be valid. Force-unwrapping an invalid conversion causes a runtime error.
Common Swift String-to-Int Conversion Results
| String value | Conversion | Result |
|---|---|---|
"256" | Int("256") | Optional(256) |
"-25" | Int("-25") | Optional(-25) |
"12.5" | Int("12.5") | nil |
"25 items" | Int("25 items") | nil |
"FF" | Int("FF", radix: 16) | Optional(255) |
"" | Int("") | nil |
Swift String-to-Int Editorial QA Checklist
- Confirm every example treats
Int(String)as an optional result. - Verify invalid-input examples return
nilinstead of implying partial parsing. - Use
if letorguard letwhere force-unwrapping is unnecessary. - Check that radix examples use only digits valid for the specified number base.
- Keep decimal-string conversion separate from integer-string conversion and state the truncation or rounding behavior clearly.
Swift String to Int Frequently Asked Questions
How do I convert a String to an Int in Swift?
Call Int(string) and unwrap the returned optional. A common pattern is if let number = Int(string) { ... }.
Why does Int(String) return nil in Swift?
It returns nil when the complete string is not a valid integer in the requested radix or when the represented value cannot be stored as an Int. Examples include letters in a decimal string, an empty string, and a decimal value such as "4.5".
How do I remove the optional from a converted Swift Int?
Use optional binding with if let, early validation with guard let, or the nil-coalescing operator when a fallback value is appropriate. Force-unwrapping with ! should be reserved for input that is guaranteed to be valid.
Can Swift convert a hexadecimal String to Int?
Yes. Pass radix 16, as in Int("FF", radix: 16). This returns an optional containing 255.
How do I convert a decimal String to an Int in Swift?
Convert the string to Double first, then convert the resulting number to Int using the truncation or rounding behavior required by the program. Int("12.5") itself returns nil.
Swift String-to-Integer Conversion Summary
In this Swift Tutorial, we learned how to convert a String to Integer in Swift programming. Use Int(string) for integer text, handle the optional result safely, trim external input when necessary, specify a radix for non-decimal numbers, and parse decimal strings with an appropriate floating-point type first.
TutorialKart.com