How do I save an Int array in Swift using NSUserDefaults?
You should use if let
to unwrap your optional value and also a conditional cast. By the way you should also use arrayForKey
as follow:
if let loadedArray = UserDefaults.standard.array(forKey: "myArray") as? [Int] {
print(loadedArray)
}
Or use the nil coalescing operator ??
:
let loadedArray = UserDefaults.standard.array(forKey: "myArray") as? [Int] ?? []
Swift 4:
myArray : [Int] = UserDefaults.standard.object(forKey: "myArray") as! [Int]
You want to assign an AnyObject?
to an array of Int
s, 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
}