Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 386
Cesare Avatar asked Jan 28 '15 16:01

Cesare


2 Answers

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] ?? []
like image 123
Leo Dabus Avatar answered Nov 15 '22 21:11

Leo Dabus


Swift 4:

myArray : [Int] = UserDefaults.standard.object(forKey: "myArray") as! [Int]
like image 45
smohn Avatar answered Nov 15 '22 22:11

smohn