展开可选值 NSDefautlts 时发现 nil 的 Swift 问题 [英] Swift issue with nil found while unwrapping an Optional value NSDefautlts

查看:63
本文介绍了展开可选值 NSDefautlts 时发现 nil 的 Swift 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如果我预先填充数据,则有效.但我想允许一个 nil 值.

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

推荐答案

stringForKey 返回一个可选项,因此您可以使用 nil 合并运算符??"在 nil 的情况下返回一个空字符串 "":

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") ?? ""

这篇关于展开可选值 NSDefautlts 时发现 nil 的 Swift 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆