user934902
user934902

Reputation: 1204

Swift error unwrapping nil when data is present

I am passing a User object into another segue. For whatever reason I can print out the object and view all the information in the console. I can even unwrap the data but when I go to insert the data into an outlet it crashes.

var user : User? {
    didSet {
        if let name = user?.name {
            print(name)
            nameLabel.text = name
        }
    }
}

enter image description here As you can see the property exists, however as soon as I try to apply it to my IBOutlet it crashes....

enter image description here

Upvotes: 0

Views: 175

Answers (1)

Nirav D
Nirav D

Reputation: 72410

If you are setting the value from some other controller and ChatVC is not loaded then your nameLabel is nil, you can prevent crash by checking nil for it.

var user : User? {
    didSet {
        if let name = user?.name  {
            print(name)
            if nameLabel != nil {
                nameLabel.text = name
            }
        }
    }
}

Also if your setting the nameLabel where you have created instance of ChatVC then instead of doing this you need to set Label text in viewDidLoad of ChatVC like this.

override func viewDidLoad() {
    super.viewDidLoad()
    nameLabel.text = user?.name
}

Upvotes: 1

Related Questions