According to Swift - Converting String to Int, there\'s a String
method toInt()
.
But, there\'s no toUInt()
method. So, how to conv
Please, for the love of not crashing, don’t use !
to do this.
It’s easy to tack a map
on the end of toInt
to convert it to an optional UInt
:
let str = "4"
let myUInt = str.toInt().flatMap { $0 < 0 ? nil : UInt($0) }
then use the usual unwrapping techniques on myUInt
.
And if you find yourself doing this a lot:
extension String {
func toUInt() -> UInt? {
return self.toInt().flatMap { $0 < 0 ? nil : UInt($0) }
}
}
let str = "-4"
if let myUInt = str.toUInt() {
println("yay, \(myUInt)")
}
else {
println("nuh-uh")
}
edit: as @MartinR points out, while safe, this doesn’t extract the full range of possible values for a UInt
that Int
doesn’t cover, see the other two answers.