问题
@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