0

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?

1

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

Comments

1

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

It doesn't actually work with Int either. You have to have an array of Objective-C objects, and a number is not an object in Objective-C.

However, Swift bridges Int to NSNumber automatically, so it looks like it works.

It doesn't do that for Int64. You have to create the NSNumber objects yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.