Cesare Cesare - 2 years ago 118
Swift Question

How do I save an Int array in Swift using NSUserDefaults?

This is an array:

var myArray = [1]

It contains

This is how I save an array in
. This code seems to be working fine:

NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "myArray")

This is how I load an array:

myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray")

The code above, though, retrieves an error. Why?

Answer Source

You want to assign an AnyObject? to an array of Ints, beacuse objectForKey returns AnyObject?, so you should cast it to array this way:

myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray") as [Int]

If there are no values saved before, it could return nil, so you could check for it with:

if let temp = NSUserDefaults.standardUserDefaults().objectForKey("myArray") as? [Int] {
    myArray = temp
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download