Swift: How to convert String to UInt?

后端 未结 5 1009
太阳男子
太阳男子 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:35

    You might be interested in a safer solution similar to:

    let uIntString = "4"
    let nonUIntString = "foo"
    
    extension String {
        func toUInt() -> UInt? {
            let scanner = NSScanner(string: self)
            var u: UInt64 = 0
            if scanner.scanUnsignedLongLong(&u)  && scanner.atEnd {
                return UInt(u)
            }
            return nil
        }
    }
    
    uIntString.toUInt()     // Optional(4)
    nonUIntString.toUInt()  // nil
    

    Hope this helps

    // Edited following @Martin R. suggestion

提交回复
热议问题