Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, how to convert String to Int for base 2 though base 36 like Long.parseLong in Java?

Tags:

ios

swift

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

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

like image 771
YuXuan Fu Avatar asked Nov 09 '22 23:11

YuXuan Fu


2 Answers

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.

like image 191
Todd Agulnick Avatar answered Nov 14 '22 21:11

Todd Agulnick


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

like image 28
Roger Oba Avatar answered Nov 14 '22 21:11

Roger Oba