In Swift, how do I convert String to Int for base 2, although base 36 is like Long.parseLong in Java?
4 answers
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"
}
0
source to share
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
0
source to share