String to Int in Swift: From Simple to Performant
\n\nEvery iOS developer sooner or later faces a seemingly simple task: turning a string into a number. It seems like it couldn't be easier — Int("42") and you're done. But when an application processes thousands of strings, parses a JSON log, or reads user input, the performance of this operation becomes critical.
In this article, we will not just show how to convert String to Int in Swift, but also conduct a real investigation: which method is faster, what pitfalls hide behind simple code, and how to write optimized Swift code that won't let you down in production.
\n\nThe material is based on a popular Stack Overflow question (thousands of views) and adapted for the educational portal PythonLib. Let's go!
\n\n1. Basic Method: Int(string)
\n\nThe most obvious and Apple-recommended way is to use the Int(String) initializer. It returns an optional Int?, which is safe: if the string is not a number, you get nil.
let stringNumber = "123"\nif let number = Int(stringNumber) {\n print("Number: \\(number)")\n} else {\n print("Failed to convert")\n}\n\nPros:
\n- \n
- Code readability — the best of all options. \n
- Safety — the optional protects against crashes. \n
- Support for different number bases:
Int("FF", radix: 16). \n
Cons:
\n- \n
- Performance — can be a bottleneck in bulk operations. \n
- Does not handle spaces, currency symbols, or localized numbers. \n
This method is ideal for 90% of cases. But if you are writing a log parser or processing CSV files with a million rows — read on.
\n\n2. Using NumberFormatter: For "Dirty" Strings
\n\nThe real world is not perfect. A user might enter " 42 ", "$100", or "1 234.56". This is where NumberFormatter comes to the rescue — a powerful but slow tool.
let formatter = NumberFormatter()\nformatter.numberStyle = .decimal\n\nif let number = formatter.number(from: " 1 234 ")?.intValue {\n print(number) // 1234\n}\n\nWhen to use:
\n- \n
- Parsing localized numbers (European format "1.234,56"). \n
- Strings with spaces, currencies, percentages. \n
- UI input fields where the user can enter anything. \n
However, remember: NumberFormatter is heavyweight. Creating it is expensive, so always cache the instance as a static variable rather than creating it anew for each string.
3. Scanner (NSScanner) — Old but Fast
\n\nA classic approach from Objective-C — Scanner. It works faster than NumberFormatter but requires careful handling.
let scanner = Scanner(string: "123abc")\nvar intValue: Int = 0\nif scanner.scanInt(&intValue) {\n print("Found: \\(intValue)") // 123\n}\n\nScanner scans the string from left to right and stops at the first non-numeric character. This is convenient if you need to "extract" a number from a string with garbage.
\n\nBenchmark tip: Scanner is 3-5 times faster than NumberFormatter, but 2-3 times slower than simple Int(). Ideal for parsing mixed data.
4. Custom Function: Manual Parsing for Maximum Speed
\n\nIf you are reading this article on PythonLib, you probably know: when speed is needed — write it by hand. For purely numeric strings (only characters 0-9, possibly a minus sign), you can write your own parser.
\n\nfunc fastInt(from string: String) -> Int? {\n var result = 0\n var isNegative = false\n var started