5

How do I convert a String to a Long in Swift?

In Java I would do Long.parseLong("str", Character.MAX_RADIX).

vacawama
  • 150,663
  • 30
  • 266
  • 294
YuXuan Fu
  • 1,911
  • 3
  • 14
  • 13

4 Answers4

3

We now have these conversion functions built-in in Swift Standard Library:

Encode using base 2 through 36: https://developer.apple.com/documentation/swift/string/2997127-init Decode using base 2 through 36: https://developer.apple.com/documentation/swift/int/2924481-init

Roger Oba
  • 1,292
  • 14
  • 28
2

As noted here, you can use the standard library function strtoul():

let base36 = "1ARZ"
let number = strtoul(base36, nil, 36)
println(number) // Output: 60623

The third parameter is the radix. See the man page for how the function handles whitespace and other details.

Community
  • 1
  • 1
Todd Agulnick
  • 1,945
  • 11
  • 10
0

Here is parseLong() in Swift. Note that the function returns an Int? (optional Int) that must be unwrapped to be used.

// Function to convert a String to an Int?.  It returns nil
// if the string contains characters that are not valid digits
// in the base or if the number is too big to fit in an Int.

func parseLong(string: String, base: Int) -> Int? {
    let digits = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")

    var number = 0
    for char in string.uppercaseString {
        if let digit = find(digits, char) {
            if digit < base {
                // Compute the value of the number so far
                // allowing for overflow
                let newnumber = number &* base &+ digit

                // Check for overflow and return nil if
                // it did overflow
                if newnumber < number {
                    return nil
                }
                number = newnumber
            } else {
                // Invalid digit for the base
                return nil
            }
        } else {
            // Invalid character not in digits
            return nil
        }
    }
    return number
}

if let result = parseLong("1110", 2) {
    println("1110 in base 2 is \(result)")  // "1110 in base 2 is 14"
}

if let result = parseLong("ZZ", 36) {
    println("ZZ in base 36 is \(result)")   // "ZZ in base 36 is 1295"
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
-3

Swift ways:

"123".toInt() // Return an optional

C way:

atol("1232")

Or use the NSString's integerValue method

("123" as NSString).integerValue
Shuo
  • 8,447
  • 4
  • 30
  • 36