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

被刻印的时光 ゝ 提交于 2019-12-10 05:46:54

问题


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?


回答1:


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
}



回答2:


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 myLoadedArray = UserDefaults.standard.array(forKey: "myArray") as? [Int] {
    print(myLoadedArray)
}

Or use the nil coalescing operator ??:

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



回答3:


Swift 4:

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


来源:https://stackoverflow.com/questions/28197041/how-do-i-save-an-int-array-in-swift-using-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!