Swift issue with nil found while unwrapping an Optional value NSDefautlts

前端 未结 3 856
盖世英雄少女心
盖世英雄少女心 2020-12-22 09:23

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

let lastupdate = defaults.stringForKey(\"localdate\")
self.lastUpdate.tex         


        
相关标签:
3条回答
  • 2020-12-22 09:52

    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") ?? ""
    
    0 讨论(0)
  • 2020-12-22 09:57
    let lastupdate = defaults.stringForKey("localdate")
    self.lastUpdate.text = {
        if let date = lastupdate {
            return "Updated at \(date)"
        }
        return "Not yet updated"
    }()
    
    0 讨论(0)
  • 2020-12-22 10:06

    Try this,

    if let lastupdate = userDefaults.stringForKey("localdate"){
        self.lastUpdate.text = "Updated at " + lastupdate
        } else {
            println("nil value")
            // do what ever u want
        }
    
    0 讨论(0)
提交回复
热议问题