Swift NSUserDefaults NSArray using objectForKey

会有一股神秘感。 提交于 2019-12-06 06:15:17

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.

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