Swift隐式转换类型

时间:2016-03-15 17:44:56

标签: swift swift2

我们说我已经宣布UIViewController为我班上的财产。在某些情况下,我们可以隐式地将UINavigationController分配给此属性。

UIViewController *someNavigationController

在Objective-C中,我可以简单地指定

UIViewController *vc = self.someNavigationController;

if (vc)
{
 //then do something
}

正如我在Swift中所理解的,如果我的self.centerViewController声明为UIViewController,我应该这样做。右

let nvc = self.centerViewController as! UINavigationController

Alos我该怎么检查

if nvc != nil

它说它不能为零。

2 个答案:

答案 0 :(得分:3)

你也可以这样检查: -

if self.centerViewController is UINavigationController 
{
 // here self.centerViewController must be an instance of UINavigationController and not nil
  let nvc = self.centerViewController as! UINavigationController
} 
else {
      // here May be nil or may be an instance is of an other class
}

答案 1 :(得分:2)

as! UINavigationController意味着它是一个被迫向下压缩:它已被解包,它不再是一个可选项,因此它不能再为零 - 如果它 为零(或不是向下的) ),它会破坏应用程序。

您可以使用可选绑定:

if let nvc = self.centerViewController as? UINavigationController {
  // here, nvc is not nil and is a UINavigationController, you can use it
} else {
  // here, either self.centerViewController is nil or we can't cast it as a UINavigationController
}