Converting large Int from String

What seems to be something that should be fairly trivial has been causing me quite a bit of issues. I am attempting to convert a large integer to the Int type from a String. Basically I have a 64 bit hash that at one point gets passed around as a String and I need to convert it back to an Int.

According to all documentation I could find, in Swift the Int type is 64bits. Calling, Int(str) should handle 64bit conversions just fine. But it seems that it's trying to convert it to a 32bit integer so I receive a nil value. I'm unable to use Int64() for various reasons (long story short the key in my hash table has to be of type Int not Int64).

Here is what the code looks like:

Declared at the start of the class:

var nameTable: Dictionary<Int, String> = [:]

Declared later in some function:

let kv = data[i].componentsSeparatedByString(":")
self.nameTable[Int(kv[0])!] = kv[1]

Where kv[0]="3928953869951869841" and kv[1]="a" the piece Int(kv([0])! fails because a nil value is returned when it was unexpected.

Int.max returns a value of 2147483647, the 32bit max int, which strikes me as odd considering all docs state int as a 64bit value. Code has been run on iPhones 5 - 6s, all with the same result.

Any help would be greatly appreciated. Thanks!


Int("string") - is optional type If you want to exclude nil exception, try this code:

    let stingNumber = "3928953869951869841"
    if let index = Int64("(stingNumber)") {
        self.nameTable[index] = "a"
        NSLog("(self.nameTable)")
        NSLog("(Int64.max)")
    }

I was simulated this on iPhone 4s and i had log:

2016-08-10 15:22:24.199 stackoverlow-38866748[52907:1401199] [3928953869951869841: "a"] 
2016-08-10 15:22:24.202 stackoverlow-38866748[52907:1401199] 9223372036854775807

See Int in the Apple Developer Documentation:

On 32-bit platforms, Int is the same size as Int32 , and on 64-bit platforms, Int is the same size as Int64 .

3928953869951869841 exceeds the range for 32-bit integers. Therefore, in order to store that value in an integer, you have to use Int64 (or UInt64 ), there is no way around it (unless the app is restricted to 64-bit devices only).

Note also that the documentation for hashValue() states:

Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.

链接地址: http://www.djcxy.com/p/24354.html

上一篇: 在Windows Azure中配置SSL

下一篇: 从字符串转换大型Int