Swift issue with nil found while unwrapping an Opt

2020-02-16 02:55发布

问题:

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
    }