unexpectedly found nil while unwrapping an Optional

依然范特西╮ 提交于 2020-06-17 03:07:27

问题


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

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.


回答1:


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
        }
    }
}



回答2:


@Antonio already explained the problem. An alternative solution is

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

using optional chaining on the left-hand side of the expression. If groupNameTF is nil then the text setter method will not be called.



来源:https://stackoverflow.com/questions/26860829/unexpectedly-found-nil-while-unwrapping-an-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!