Eatton Eatton - 3 months ago 21
iOS Question

How to save an array of Int64 variables using NSCoding in Swift

I am currently using NSCoding to save an array of Int variables like this:

var myArray = [Int]()

myArray = aDecoder.decodeObjectForKey("MyArray") as! [(Int)]

aCoder.encodeObject(myArray, forKey: "MyArray")


I now need to save an array of Int64 variables. I thought it would be simple, so I did this:

var myNewArray = [Int64]()

myNewArray = aDecoder.decodeObjectForKey("MyNewArray") as! [(Int64)]

aCoder.encodeObject(myNewArray, forKey: "MyNewArray")


However I get an error on the last line:
Cannot convert value of type '[Int64]' to expected argument type 'AnyObject?'

I am puzzled as to why it works with Int but not Int64. How can I achieve this?

Answer

In the current version of Swift, when you convert [Int] to AnyObject (or AnyObject?), Swift generates NSArray containing NSNumbers. Although NSNumber can contain Int64 (long long int in C/Objective-C), Swift does not convert Int64 to NSNumber automatically, thus, [Int64] cannot be automatically converted to AnyObject.

You can generate an NSArray containing NSNumber explicitly.

let myI64Array = aDecoder.decodeObjectForKey("MyNewArray") as! [NSNumber]
myNewArray = myI64Array.map{$0.longLongValue}

Or:

let myI64Array = myNewArray.map{NSNumber(longLong: $0)}
aCoder.encodeObject(myI64Array, forKey: "MyNewArray")
Comments