How to save Int array in Swift using NSUserDefaults?

This is an array:

var myArray = [1] 

It contains Int values.

This is how I save the array in NSUserDefaults . This code works fine:

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

This is how I load the array:

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

The above code gets an error. Why?

+5
source share
3 answers

Do you want to assign AnyObject? Int s array, beacuse objectForKey returns AnyObject? , so you should use it for the array as follows:

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

If there were no stored values ​​before, it could return zero, so you can check it with:

 if let temp = NSUserDefaults.standardUserDefaults().objectForKey("myArray") as? [Int] { myArray = temp } 
+5
source

You should use if let to expand your optional value as well as conditional casting. By the way, you should also use arrayForKey as follows:

 if let myLoadedArray = UserDefaults.standard.array(forKey: "myArray") as? [Int] { print(myLoadedArray) } 

Or use the coalescing operator nil ?? :

 let myLoadedArray = UserDefaults.standard.array(forKey: "myArray") as? [Int] ?? [] 
+3
source

Swift 4:

 myArray : [Int] = UserDefaults.standard.object(forKey: "myArray") as! [Int] 
0
source

Source: https://habr.com/ru/post/1212116/


All Articles