Swift: How to convert String to UInt?

后端 未结 5 997
太阳男子
太阳男子 2021-02-15 00:42

According to Swift - Converting String to Int, there\'s a String method toInt().

But, there\'s no toUInt() method. So, how to conv

5条回答
  •  迷失自我
    2021-02-15 01:24

    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.

提交回复
热议问题