xcode 在 Swift 中,如何将 String 转换为 Int64?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27199371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Swift, how do you convert a String to Int64?
提问by shim
I am loading in lines from a text file with very large numbers. String has the toInt method, but how do you convert a string to an Int64 which will be able to handle the large numbers?
我正在从具有非常大数字的文本文件中加载行。String 有 toInt 方法,但是如何将字符串转换为能够处理大数字的 Int64 呢?
I don't see a toInt64 method or a toLong etc. There must be a way, but I haven't found anything by searching yet.
我没有看到 toInt64 方法或 toLong 等。一定有办法,但我还没有通过搜索找到任何东西。
Alternatively I guess I could read the numbers in the string digit by digit (or by groups of digits) and then add them together with appropriate factors of ten, but that seems like overkill. Or maybe the proper way is to read the data in a binary form and convert it that way?
或者,我想我可以逐个数字(或按数字组)读取字符串中的数字,然后将它们与适当的 10 因数相加,但这似乎有点矫枉过正。或者也许正确的方法是以二进制形式读取数据并以这种方式转换?
Thanks
谢谢
回答by Laevand
As of Swift 2.1.1 you can simply initialize Int64
with String
随着斯威夫特2.1.1你可以简单地初始化Int64
与String
let number: Int64? = Int64("42")
回答by Mobile Ben
If you don't mind using NSString, you can do this
如果你不介意使用 NSString,你可以这样做
let str = "\(LLONG_MAX)"
let strAsNSString = str as NSString
let value = strAsNSString.longLongValue
Note that unlike toInt(), longLongValue will return 0 if the string is not a legal number whereas toInt() will return nil in that case.
请注意,与 toInt() 不同,如果字符串不是合法数字,则 longLongValue 将返回 0,而在这种情况下 toInt() 将返回 nil。
回答by Hal
import Darwin
let strBase10 = "9223372036854775807"
let i64FromBase10 = strtoll(strBase10, nil, 10)
let strBase16 = "0xFFFFFFFFFFFFFFFF"
let i64FromBase16 = strtoll(strBase16, nil, 16)
strtoll means STRingTOLongLong
strtoll 表示 STRingTOLongLong
回答by newacct
import Darwin
let str = ...
let i = strtoll(str, nil, 10)