Search code examples
iosswiftoptional-arguments

How to initialize a Swift ViewController that has a non optional property passed from the preceding ViewController?


How does one initialize a Swift ViewController that has a non optional property passed from the preceding ViewController?

Please assume:

That all viewControllers are connected in the mainStoryboard and that the non-optional property is set to the childViewController in the prepareForSegue method of the parent.

class ParentVC{
    override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "playlistsSegue" {
            let vc = (segue.destination as! PlaylistsVC)
            vc.set = attachedSet
            vc.title = attachedSet?.name
        }
    }
}

The set property should be non optional because the ChildVC can't do it's thing without this model object. I have it working with the property in question as an optional and this led to a bug that took some time to isolate. By forcing this property to be set as part of the initialization trouble can be avoided now and in the future because the segue pattern shows up all the time.

class ChildVC{
var set:ModelObject 
}

Solution

  • Declaring var set: ModelObject! will give you the non-optional property. While letting set the property on your own. But warning, if you use the property before setting it (Which is unlikely seeing as you're setting in prepareForSegue: your program will crash! So doing an assert like @dan suggested will be a safe test to make sure you set your variable before using it.

    class ChildVC{
         var set:ModelObject!
    
         override func viewDidLoad() {
            super.viewDidLoad()
    
            assert(set != nil)
    
         }
    
    }
    

    Then you can just keep your code in prepareForSegue: in the ParentVC The same.