【问题标题】:Swift issue with nil found while unwrapping an Optional value NSDefautlts在展开可选值 NSDefautlts 时发现 nil 的 Swift 问题
【发布时间】:2015-03-14 16:53:40
【问题描述】:

致命错误问题:在展开可选值时意外发现 nil。

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.

如果我预先填充数据,则可以使用。但我想允许一个 nil 值。

【问题讨论】:

    标签: xcode swift null xcode-6.2


    【解决方案1】:

    stringForKey 返回一个可选值,因此您可以使用 nil 合并运算符“??”在 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】:

    试试这个,

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

    【讨论】:

    • 另一个很好的回应。
    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多