Number Parsing in Swift

Our example demonstrates how to parse numbers from strings in Swift, a common task in many programs.

import Foundation

// Swift's built-in NumberFormatter class provides number parsing functionality

let formatter = NumberFormatter()

// Parse a float
if let f = Double("1.234") {
    print(f)
}

// Parse an integer
if let i = Int("123") {
    print(i)
}

// Parse a hexadecimal number
if let d = Int("0x1c8", radix: 16) {
    print(d)
}

// Parse an unsigned integer
if let u = UInt("789") {
    print(u)
}

// Swift doesn't have a direct equivalent to Go's Atoi,
// but we can use Int initializer for basic base-10 int parsing
if let k = Int("135") {
    print(k)
}

// Parsing functions return nil on bad input
if let _ = Int("wat") {
    print("Successful parse")
} else {
    print("Failed to parse")
}

Let’s run our program:

$ swift number-parsing.swift
1.234
123
456
789
135
Failed to parse

In Swift, we use optional binding (if let) to safely unwrap the optional values returned by parsing functions. If the parsing fails, the if let condition will be false, and the code inside the block won’t be executed.

Swift’s Double and Int types have initializers that can parse strings. For hexadecimal numbers, we use the Int initializer with a radix parameter.

Unlike Go, Swift doesn’t have separate unsigned integer parsing functions. Instead, you can use the UInt type’s initializer.

Swift doesn’t have a direct equivalent to Go’s Atoi function, but the Int initializer serves the same purpose for basic base-10 integer parsing.

When parsing fails in Swift, the initializers return nil instead of an error object. You can use optional binding or nil-coalescing operators to handle these cases.

Next, we’ll look at another common parsing task: URLs.