This is an array:
var myArray = [1]
It contains Int
values.
This is how I save an array in NSUserDefaults
. 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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With