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)
        }
    }
4

2 回答 2

0

如果您真的想确保可选值不是 nil ,则似乎没有必要创建两个变量:

override func perform() {
    if let svc = self.sourceViewController as? UIViewController, 
           dvc = self.destinationViewController as? UIViewController {
        svc.navigationController?.pushViewController(dvc, animated: true)
    }
}
于 2015-08-06T12:25:10.497 回答
0

如果视图控制器是 Interface Builder 中设计的 segue 的一部分,并且您实际上知道它们不是 nil,则可以打开它们

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

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

否则,如果源控制器可以为 nil,则只有在控制器不为 nil 时才会执行 push 命令,这就像nil在 Objective-C 中发送消息一样

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

        svc.navigationController?.pushViewController(dvc, animated: true)
    }
于 2015-08-06T12:22:08.043 回答