0

If I need to perform a method whose multiple parameters' original source are optional, is doing multiple optional binding before performing the method the cleanest way to go about this?

e.g. UIStoryboardSegue's sourceViewController and destionationViewController are both AnyObject? and I need to use source's navigationController to perform something.

 override func perform() {
        var svc = self.sourceViewController as? UIViewController
        var dvc = self.destinationViewController as? UIViewController

        if let svc = svc, dvc = dvc {
            svc.navigationController?.pushViewController(dvc, animated: true)
        }
    }
Boon
  • 40,656
  • 60
  • 209
  • 315

2 Answers2

0

If the view controllers are part of a designed segue in Interface Builder and you actually know that they are not nil, you can unwrap them

override func perform() {
        var svc = self.sourceViewController as! UIViewController
        var dvc = self.destinationViewController as! UIViewController

        svc.navigationController!.pushViewController(dvc, animated: true)
    }

otherwise if the source controller could be nil, the push command will only be executed if the controller is not nil, it's like sending a message to nil in Objective-C

override func perform() {
        var svc = self.sourceViewController as? UIViewController
        var dvc = self.destinationViewController as? UIViewController

        svc.navigationController?.pushViewController(dvc, animated: true)
    }
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Since a segue can only come into existence in a storyboard, therefore forced unwrapping should never fail, right? – Boon Aug 06 '15 at 12:25
  • Yes, segues can also be created in code, but in Interface Builder they are safe. – vadian Aug 06 '15 at 12:28
0

It seems unnecessary to create two vars, if you really want to be sure that the optional values are not nil you could use:

override func perform() {
    if let svc = self.sourceViewController as? UIViewController, 
           dvc = self.destinationViewController as? UIViewController {
        svc.navigationController?.pushViewController(dvc, animated: true)
    }
}
NullPointer
  • 442
  • 3
  • 7