string - Swift:如何将 String 转换为 UInt?

标签 string swift type-conversion uint

根据 Swift - Converting String to Int ,有一个 String 方法 toInt()

但是,没有toUInt() 方法。那么,如何将 String 转换为 Uint 呢?

最佳答案

Swift 2/Xcode 7 更新:

从 Swift 2 开始,所有整数类型都有一个(可失败的)构造函数

init?(_ text: String, radix: Int = default)

它取代了 StringtoInt() 方法,所以没有自定义 此任务不再需要代码:

print(UInt("1234")) // Optional(1234)
// This is UInt.max on a 64-bit platform:
print(UInt("18446744073709551615")) // Optional(18446744073709551615)
print(UInt("18446744073709551616")) // nil (overflow)
print(UInt("1234x")) // nil (invalid character)
print(UInt("-12")) // nil (invalid character)

Swift 1.x 的旧答案:

这看起来有点复杂,但应该适用于 全范围的UInt,并正确检测所有可能的错误 (例如溢出或尾随无效字符):

extension String {
    func toUInt() -> UInt? {
        if contains(self, "-") {
            return nil
        }
        return self.withCString { cptr -> UInt? in
            var endPtr : UnsafeMutablePointer<Int8> = nil
            errno = 0
            let result = strtoul(cptr, &endPtr, 10)
            if errno != 0 || endPtr.memory != 0 {
                return nil
            } else {
                return result
            }
        }
    }
}

备注:

  • BSD库函数strtoul用于转换。 endPtr 设置为输入字符串中的第一个“无效字符”, 因此 endPtr.memory == 0 如果 all 个字符必须保留 可以转换。 在转换错误的情况下,设置全局 errno 变量 为非零值(例如,ERANGE 表示溢出)。

  • 减号测试是必要的,因为 strtoul() 接受 负数(用 相同的位模式)。

  • Swift 字符串在“幕后”转换为 C 字符串 传递给采用 char * 参数的函数,因此可以是 试图调用 strtoul(self, &endPtr, 0)(这是我在 这个答案的第一个版本)。问题是自动 创建的 C 字符串只是临时的,当 strtoul() 返回,这样 endPtr 就不会指向一个 输入字符串中的字符了。当我在 Playground 中测试代码时发生了这种情况。使用self.withCString { ... },不会出现这个问题,因为C字符串在整个执行过程中都是有效的 关闭。

一些测试:

println("1234".toUInt()) // Optional(1234)
// This is UInt.max on a 64-bit platform:
println("18446744073709551615".toUInt()) // Optional(18446744073709551615)
println("18446744073709551616".toUInt()) // nil (overflow)
println("1234x".toUInt()) // nil (invalid character)
println("-12".toUInt()) // nil (invalid character)

关于string - Swift:如何将 String 转换为 UInt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30382414/

相关文章:

java - Integer.toString() 和 String.valueOf() 之间的性能差异?

ios - NSInvalidArgumentException : Workout_Tracker. QuickAddViewController collectionView:numberOfItemsInSection:]:无法识别的选择器发送到实例

c - 如何将无符号整数转换为 float ?

swift - 如何将 Sprite 添加到 View Controller ?

ios - 按下导航栏中的后退按钮并弹出 View B 后更新 View B 后面的 View A

c - 如何解决c类型转换中的这个错误?

c++ - 为什么按位否定运算符 "~"转换为 int? (从 ‘unsigned char’ 转换为 ‘int’ 可能会改变它的值)

C#:最易读的字符串连接。最佳实践

c++ - 字符串(从 substr)转换为 unsigned int

c - 在 C 中使用字符串数组