简体   繁体   English

在Swift中,如何将String转换为Int64?

[英]In Swift, how do you convert a String to Int64?

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. 或者我想我可以用数字(或数字组)读取字符串中的数字,然后将它们与适当的因子10一起添加,但这看起来有点过分。 Or maybe the proper way is to read the data in a binary form and convert it that way? 或者正确的方法是以二进制形式读取数据并以这种方式转换它?

Thanks 谢谢

从Swift 2.1.1开始,您只需使用String初始化Int64即可

let number: Int64? = Int64("42")

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。

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

http://www.freebsd.org/cgi/man.cgi?query=strtoll http://www.freebsd.org/cgi/man.cgi?query=strtoll

import Darwin
let str = ...
let i = strtoll(str, nil, 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM