In Swift, how do I convert String to Int for base 2, although base 36 is like Long.parseLong in Java?
How can I convert String to Long in Swift?
In Java, I would do Long.parseLong("str", Character.MAX_RADIX)
.
As stated here , you can use the strtoul () standard library function:
let base36 = "1ARZ"
let number = strtoul(base36, nil, 36)
println(number) // Output: 60623
The third parameter is the base. See the man page for how the function handles spaces and other data.
Here parseLong()
at Swift. Note that the function returns Int?
(optional Int
) which must be unwrapped for use.
// 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"
}
We now have built-in conversion functions in the Swift standard library:
Encoding using base 2-36: https://developer.apple.com/documentation/swift/string/2997127-init Decoding using base 2-36: https://developer.apple.com/documentation/swift/int / 2924481 -in this
Fast ways:
"123".toInt() // Return an optional
C way:
atol("1232")
Or use integerValue NSString method
("123" as NSString).integerValue