Swift issue with nil found while unwrapping an Optional value NSDefautlts

我的未来我决定 提交于 2019-11-28 12:17:25

问题


Issue with fatal error: unexpectedly found nil while unwrapping an Optional value.

let lastupdate = defaults.stringForKey("localdate")
self.lastUpdate.text = "Updated at " + last update! //issues when I use this line
self.lastUpdate.text = lastupdate // If use this line I have no issues.

Works if I pre populate the data. But I would like to allow a nil value.


回答1:


stringForKey returns an optional, so you can use the nil coalescing operator "??" to return an empty string "" in case of nil:

let lastupdate = defaults.stringForKey("localdate") ?? ""



回答2:


let lastupdate = defaults.stringForKey("localdate")
self.lastUpdate.text = {
    if let date = lastupdate {
        return "Updated at \(date)"
    }
    return "Not yet updated"
}()



回答3:


Try this,

if let lastupdate = userDefaults.stringForKey("localdate"){
    self.lastUpdate.text = "Updated at " + lastupdate
    } else {
        println("nil value")
        // do what ever u want
    }


来源:https://stackoverflow.com/questions/29051588/swift-issue-with-nil-found-while-unwrapping-an-optional-value-nsdefautlts

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