Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

like image 775
shim Avatar asked Nov 29 '14 05:11

shim


People also ask

How do I convert text to Int in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do I convert a string to a float in Swift?

If the String contains a valid floating point value, then Swift will assign it to the floatValue constant which will be available within the if let scope. The result of this example will be printed as “Float value = 12.2416”.

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.


2 Answers

As of Swift 2.1.1 you can simply initialize Int64 with String

let number: Int64? = Int64("42")
like image 140
Laevand Avatar answered Sep 18 '22 02:09

Laevand


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.

like image 35
Mobile Ben Avatar answered Sep 22 '22 02:09

Mobile Ben