Swift issue with nil found while unwrapping an Opt

2020-02-16 02:35发布

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.

3条回答
唯我独甜
2楼-- · 2020-02-16 03:14

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") ?? ""
查看更多
家丑人穷心不美
3楼-- · 2020-02-16 03:22

Try this,

if let lastupdate = userDefaults.stringForKey("localdate"){
    self.lastUpdate.text = "Updated at " + lastupdate
    } else {
        println("nil value")
        // do what ever u want
    }
查看更多
对你真心纯属浪费
4楼-- · 2020-02-16 03:28
let lastupdate = defaults.stringForKey("localdate")
self.lastUpdate.text = {
    if let date = lastupdate {
        return "Updated at \(date)"
    }
    return "Not yet updated"
}()
查看更多
登录 后发表回答