What does it mean when an optional variable is <uninitialized> in a view controller?

Viewed 182

I have a view controller that shows detail for my "SkillGroup" entity. I want to use this for both viewing and editing/creating a "SkillGroup". Thus I have an optional variable skillGroup which is either unset - and nil when you are first creating the SkillGroup and before you save it, OR it is set and you will be simply viewing the SkillGroup. Here is my code

class GroupViewController:UIViewController { 
    
    var skillGroup: SkillGroup?
    override func viewDidLoad() {
        super.viewDidLoad()
        if let skillGroup = skillGroup {
            self.title = skillGroup.name
        }
    }
}

and in the previous view controller:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "createGroupSegue" {
        let destination = segue.destination as? GroupViewController
        destination?.createOrEdit = true
    }
    if segue.identifier == "showGroupSegue" {
        if let selectedGroupPath = self.groupsTableView.indexPathForSelectedRow {
            let destination = segue.destination as? GroupViewController
            destination?.createOrEdit = false
            let group = groups[selectedGroupPath.row]
            destination?.skillGroup = group
        }
    }
}

If I set a breakpoint right after the call to super, and I inspect skillGroup, it says its <uninitialized>. I don't think this because its "nil" like a normal optional variable that hasn't been set. Additionally I did set the skillGroup variable in the prepare for segue code.

I really can't find much information on what means. Can someone help me out here?

1 Answers

I think you are inspecting the wrong variable in the debugger (the local variable instead of the instance variable).

I made a quick sample:

class ViewController: UIViewController {
  public class TestClass {
    var foo: String
    var bar: Int
    
    init() {
      foo = "foo"
      bar = 4711
    }
  }
  
  public var test: TestClass?
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    test = TestClass()
    
    if let test = test {
      print(test.foo)
    }
  }
}

When I set a breakpoint on the line if let test = test { I will see the following in the debugger:

debugger

Here you can see that it will print <uninitialized> when I print the description of the local test variable because the let statement on that line was not executed yet.

Please note that there is a local variable (only living inside the if scope) and an instance variable. In the debugger you will see the instance variables when you expand the self node.

Related