In Swift, how do you convert a String to Int64?
Asked Answered
C

4

24

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?

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.

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?

Thanks

Crist answered 29/11, 2014 at 5:56 Comment(2)
If you compile as a 64-bit app then Int is a 64-bit integer.Dworman
While the answers below are perfectly valid, in my case @MartinR 's answer was the most helpful. If you add it as an answer I can give you the answer credit.Crist
D
48

As of Swift 2.1.1 you can simply initialize Int64 with String

let number: Int64? = Int64("42")
Debi answered 30/3, 2016 at 13:38 Comment(2)
I don't think this words in Swift 4Wsan
Seems to be working fine for me (Swift 5)Crist
T
10

If you don't mind using NSString, you can do this:

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.

Tintoretto answered 29/11, 2014 at 6:32 Comment(2)
I'm trying to do this same thing but get an unsigned Int64. I tried looking through NSString but unfortunately theres no methods that return an UInt64. I was wondering if you had any ideas? Maybe it should be a new question?Genovera
@Genovera you can use the C function strtoull. Example: strtoull(str, nil, 10). The first parameter is the string and the third parameter is the base to convert from. I don't know what the second parameter dose.Caitiff
E
4
import Darwin

let strBase10 = "9223372036854775807"
let i64FromBase10 = strtoll(strBase10, nil, 10)

let strBase16 = "0xFFFFFFFFFFFFFFFF"
let i64FromBase16 = strtoll(strBase16, nil, 16)

strtoll means STRingTOLongLong

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

Explorer answered 8/4, 2015 at 4:28 Comment(0)
P
1
import Darwin
let str = ...
let i = strtoll(str, nil, 10)
Philodendron answered 29/11, 2014 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.