Shmidt
Shmidt

Reputation: 16684

unexpectedly found nil while unwrapping an Optional

@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.

Upvotes: 1

Views: 818

Answers (2)

Martin R
Martin R

Reputation: 540055

@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.

Upvotes: 4

Antonio
Antonio

Reputation: 72780

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

Upvotes: 4

Related Questions