Skip to content

Instantly share code, notes, and snippets.

@chug2k
Created February 25, 2017 19:04
Show Gist options
  • Save chug2k/146e284c11676521bd5de2da5693762f to your computer and use it in GitHub Desktop.
Save chug2k/146e284c11676521bd5de2da5693762f to your computer and use it in GitHub Desktop.
Initializing a View Controller
  if let destinationViewController = segue.destination as? AddGuestsViewController {
     destinationViewController.event = event
     destinationViewController.isOwner = isOwner
     destinationViewController.limit = limit
  }

This is taken from GuestsViewController.swift. I arrived at this code from the AddGuestsViewController, because I wasn't sure who was setting the value of the event: Event! member of that controller.

I don't think this code is really bad, but a few quick notes:

  • I had to search for the place where it could be set, but not very efficiently.
  • It's possible for the caller to forget to set one of these methods.

Off the top of my head, I can't really think of a better way to handle this. We could do some sort of complicated protocol, but I think the easiest way: let's define a standard (candidate for Knowledge Base) where we add an initUI function (something I've seen from Huy's code). Let's figure out what we call it, whether it be initUI, setup, initVC, prepare, whatever - and let's call it the same method everywhere (our standard VC template should have this method, with a comment with something like // MARK - Initialize class variables after initialization.

The main benefit of this is it would force callers to know that you have to set all three variables in the above. For example, right now I'm about to add a new variable that must be set. Right now, it's only called in one place, but if there were multiple callers who were initializing this VC, I would just have unwittingly broken one of them.

@chug2k
Copy link
Author

chug2k commented Feb 25, 2017

(We could have a protocol that defines this setup method that all of our view controllers implement, but that seems like too much)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment