gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:40:37 26 4
gpt4 key购买 nike

根据 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com