Number Parsing in Swift
Our example demonstrates how to parse numbers from strings in Swift, a common task in many programs.
Let’s run our program:
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.