Get integer value from string in swift
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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()
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
The nil-coalescing operator ?? provides a fallback value when parsing fails, avoiding force-unwrapping.
Parsing Different Number Bases
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
NumberFormatter handles locale-specific formatting that Int() cannot parse — thousands separators, decimal commas, currency symbols, and percentage signs.
Trimming Whitespace Before Parsing
Extracting Numbers from Mixed Strings
Converting Between Integer Types
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 useif let,guard let, or??to handle thenilcase. User input and API responses are never guaranteed to be valid integers. - Expecting
Int()to trim whitespace:Int(" 42")returnsnil, not42. Call.trimmingCharacters(in: .whitespacesAndNewlines)on the string before parsing. - Confusing
Int()withDouble()for decimal strings:Int("3.14")returnsnil. If you need to truncate a decimal string to an integer, parse asDoublefirst and then convert:Int(Double("3.14")!). - Using
atoiorNSString.intValuefrom Objective-C:NSString.intValuereturns0for invalid input instead ofnil, silently hiding errors.atoihas the same problem. Always use Swift's failableInt()initializer for safe parsing. - Ignoring overflow for specific integer types:
Int8("200")returnsnilbecause 200 exceedsInt8.max(127). When parsing into narrow types, check the range or useIntfirst and then validate withInt8(exactly:).
Summary
- Use
Int("string")for basic string-to-integer conversion — returnsInt?(optional) - Use
??for default values:Int(input) ?? 0 - Use
Int("FF", radix: 16)for hex, binary, and other bases - Use
NumberFormatterfor 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
Related reading
- Get lighter and darker color variations for a given UIColor
- Get notified when UITableView has finished asking for data?
- Get nth character of a string in Swift
- Get position of UIView in respect to its superview's superview
- Get push notification while App in foreground iOS
- Get real path from URI, Android KitKat new storage access framework
- Get root view from current activity
- Get safe area inset top and bottom heights
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.