Swift NSUserDefaults NSArray using objectForKey

2019-05-27 05:05发布

问题:

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.