Swift
String Conversion
Integer Parsing
Swift Programming
iOS Development

Get integer value from string in swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Swift converts strings to integers using the failable Int() initializer, which returns an optional Int?. If the string contains a valid integer representation, you get the value; otherwise, you get nil. This design forces you to handle invalid input explicitly — there is no silent conversion to zero or crash on failure. For different number bases (hex, octal, binary), use Int("FF", radix: 16). For strings with whitespace, currency symbols, or locale-specific formatting, use NumberFormatter.

Basic Conversion with Int()

swift
1// Simple conversion — returns Int?
2let number = Int("42")        // Optional(42)
3let invalid = Int("hello")    // nil
4let decimal = Int("3.14")     // nil — Int does not parse decimals
5let empty = Int("")            // nil
6let negative = Int("-7")       // Optional(-7)
7let whitespace = Int(" 42 ")  // nil — no whitespace trimming
8
9// Unwrap with if-let
10if let value = Int("42") {
11    print("Parsed: \(value)")  // "Parsed: 42"
12} else {
13    print("Invalid number")
14}
15
16// Unwrap with guard
17func processInput(_ input: String) -> Int {
18    guard let value = Int(input) else {
19        fatalError("Expected a valid integer, got: \(input)")
20    }
21    return value
22}

Int() is strict — it requires the entire string to be a valid integer with no extra characters, whitespace, or decimal points.

Default Values with nil-Coalescing

swift
1// Provide a default when parsing fails
2let count = Int("abc") ?? 0           // 0
3let port = Int(portString) ?? 8080    // 8080 if invalid
4let page = Int(pageParam) ?? 1        // 1 if missing or invalid
5
6// Useful in SwiftUI / UIKit text field handling
7let textField = UITextField()
8textField.text = "25"
9let age = Int(textField.text ?? "") ?? 0  // 25

The nil-coalescing operator ?? provides a fallback value when parsing fails, avoiding force-unwrapping.

Parsing Different Number Bases

swift
1// Hexadecimal
2let hex = Int("FF", radix: 16)       // Optional(255)
3let hexPrefix = Int("0xFF", radix: 16)  // nil — "0x" prefix not supported
4let hexClean = Int("FF".replacingOccurrences(of: "0x", with: ""), radix: 16)  // 255
5
6// Binary
7let binary = Int("1010", radix: 2)   // Optional(10)
8
9// Octal
10let octal = Int("77", radix: 8)      // Optional(63)
11
12// Base 36 (0-9 + a-z)
13let base36 = Int("z", radix: 36)     // Optional(35)

The radix parameter accepts values from 2 to 36. Letters are case-insensitive ("ff" and "FF" both parse as 255 in base 16).

NumberFormatter for Locale-Aware Parsing

swift
1import Foundation
2
3// Parse numbers with thousands separators, currency, etc.
4let formatter = NumberFormatter()
5formatter.numberStyle = .decimal
6formatter.locale = Locale(identifier: "en_US")
7
8let number = formatter.number(from: "1,234,567")?.intValue  // Optional(1234567)
9
10// European format (period as thousands separator)
11formatter.locale = Locale(identifier: "de_DE")
12let german = formatter.number(from: "1.234.567")?.intValue   // Optional(1234567)
13
14// Currency
15formatter.numberStyle = .currency
16formatter.locale = Locale(identifier: "en_US")
17let price = formatter.number(from: "$99")?.intValue           // Optional(99)

NumberFormatter handles locale-specific formatting that Int() cannot parse — thousands separators, decimal commas, currency symbols, and percentage signs.

Trimming Whitespace Before Parsing

swift
1let input = "  42  \n"
2
3// Int() fails with whitespace
4let direct = Int(input)  // nil
5
6// Trim first
7let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
8let value = Int(trimmed)  // Optional(42)
9
10// One-liner
11let result = Int(input.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 0

Extracting Numbers from Mixed Strings

swift
1import Foundation
2
3let text = "Order #12345 confirmed"
4
5// Using Scanner
6let scanner = Scanner(string: text)
7scanner.charactersToBeSkipped = CharacterSet.decimalDigits.inverted
8var number: Int = 0
9scanner.scanInt(&number)
10print(number)  // 12345
11
12// Using regular expressions (Swift 5.7+)
13if let match = text.firstMatch(of: /\d+/) {
14    let extracted = Int(match.output)  // Optional(12345)
15}
16
17// Extract ALL numbers
18let allNumbers = text.matches(of: /\d+/).compactMap { Int($0.output) }
19print(allNumbers)  // [12345]

Converting Between Integer Types

swift
1let intValue = Int("42")!           // Int (platform-dependent: 32 or 64 bit)
2let int8 = Int8("127")              // Optional(127) — max is 127
3let int8Overflow = Int8("128")      // nil — exceeds Int8.max
4let uint = UInt("42")               // Optional(42)
5let uintNeg = UInt("-1")            // nil — unsigned cannot be negative
6let int64 = Int64("9223372036854775807")  // Optional(Int64.max)
7
8// Convert between types
9if let intVal = Int("1000"), let uint8Val = UInt8(exactly: intVal) {
10    print(uint8Val)  // Only succeeds if value fits in UInt8
11} else {
12    print("Value out of range for UInt8")
13}

Each integer type (Int8, Int16, Int32, Int64, UInt, etc.) has its own failable init(_ description: String). Parsing fails if the value exceeds the type's range.

Common Pitfalls

  • Force-unwrapping Int() without validation: Int("abc")! crashes at runtime. Always use if let, guard let, or ?? to handle the nil case. User input and API responses are never guaranteed to be valid integers.
  • Expecting Int() to trim whitespace: Int(" 42") returns nil, not 42. Call .trimmingCharacters(in: .whitespacesAndNewlines) on the string before parsing.
  • Confusing Int() with Double() for decimal strings: Int("3.14") returns nil. If you need to truncate a decimal string to an integer, parse as Double first and then convert: Int(Double("3.14")!).
  • Using atoi or NSString.intValue from Objective-C: NSString.intValue returns 0 for invalid input instead of nil, silently hiding errors. atoi has the same problem. Always use Swift's failable Int() initializer for safe parsing.
  • Ignoring overflow for specific integer types: Int8("200") returns nil because 200 exceeds Int8.max (127). When parsing into narrow types, check the range or use Int first and then validate with Int8(exactly:).

Summary

  • Use Int("string") for basic string-to-integer conversion — returns Int? (optional)
  • Use ?? for default values: Int(input) ?? 0
  • Use Int("FF", radix: 16) for hex, binary, and other bases
  • Use NumberFormatter for locale-aware parsing (thousands separators, currency)
  • Trim whitespace before parsing: Int(str.trimmingCharacters(in: .whitespacesAndNewlines))
  • Each integer type (Int8, UInt, Int64) has its own failable initializer with range checking

Course illustration
Course illustration

All Rights Reserved.