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

Shmidt
  • 16,436
  • 18
  • 88
  • 136
  • 2
    Is maybe `groupNameTF` nil? – Antonio Nov 11 '14 at 08:47
  • @Antonio yes, you're absolutely right. – Shmidt Nov 11 '14 at 08:49
  • Possible duplicate of: [What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – pkamb May 23 '20 at 19:04

2 Answers2

4

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
        }
    }
}
Antonio
  • 71,651
  • 11
  • 148
  • 165
  • Actually, I think, in this case it should fail hard. `groupNameTF` is an outlet. The main reason why it might be `nil` is you forgot to connect it in interface builder. – JeremyP Feb 20 '20 at 15:47
  • @JeremyP another option is that outlets have not been connected yet - it can happen when you create the view (or view controller) by code, and right after you set that property. Outlets will be bound at a later stage in the view lifecycle. – Antonio Feb 20 '20 at 17:05
4

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

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382