Swift NSUserDefaults NSArray using objectForKey

亡梦爱人 提交于 2019-12-08 01:04:36

问题


I'm pretty new to Swift, and I've managed to get pretty stuck.

I'm trying to retrieve data from NSUserDefaults and store it in an array (tasks):

@lazy var tasks: NSArray = {
    let def = NSUserDefaults.standardUserDefaults()
    let obj: AnyObject? = def.objectForKey("tasks")
    return obj as NSArray
}()

All I'm getting is a warning: EXE_BAD_INSTRUCTION on line 3.

Also to note that I haven't actually set any data yet, but what I'm aiming for is that if there is no data, I want the array to be empty. I'll be using the data to populate a table view.

Now using a var instead of a constant:

@lazy var tasks: NSArray = {
    let def = NSUserDefaults.standardUserDefaults()
    var obj: AnyObject? = {
        return def.objectForKey("tasks")
    }()
    return obj as NSArray
}()

The error has now moved to the return line.


回答1:


I think the problem here is that you are attempting to cast nil to a non-optional type and return it. Swift does not allow that. The best way to solve this would be the following:

@lazy tasks: NSArray = {
    let defaults = NSUserDefaults.standardUserDefaults()
    if let array = defaults.arrayForKey("tasks") as? NSArray {
        return array
    }
    return NSArray()
}

Using Swift's if let syntax combined with the as? operator lets you assign and safe cast in one line. Since your method does not return an optional, you must return a valid value if that cast fails.



来源:https://stackoverflow.com/questions/24598991/swift-nsuserdefaults-nsarray-using-objectforkey

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