展开Optional时意外发现nil [英] unexpectedly found nil while unwrapping an Optional

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

问题描述

@IBOutlet weak var groupNameTF: UITextField!
var group: Group? {
    didSet {
        groupNameTF.text = group?.name
    }
}

无法理解此处的可选问题.从日志中可以看到,group不是nil.正如我认为的那样,我确实可以安全地进行价值包装.我还检查了if let的构造,结果相同.

Can't understand what the problem with optional here. As I see from logs, group isn't nil. As I thought I do safe value unwrapping. I also checked with if let construction, same result.

推荐答案

由于groupNameTF为nil,最有可能发生这种情况.一种快速的解决方法是使用if来保护它:

Most likely that happens because groupNameTF is nil. A quick workaround is to protect that with an if:

var group: Group? {
    didSet {
        if groupNameTF != nil {
            groupNameTF.text = group?.name
        }
    }
}

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

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