假设我已经将UIViewController声明为我班级中的属性。 在某些情况下,我们可以隐式地将UINavigationController分配给该属性。
UIViewController *someNavigationController在Objective-C中,我可以简单地分配
UIViewController *vc = self.someNavigationController; if (vc) { //then do something }正如我在Swift中所理解的,如果我的self.centerViewController声明为UIViewController我应该做这样的事情。 对
let nvc = self.centerViewController as! UINavigationControllerAlos我怎么检查
if nvc != nil它说它不能为零。
Let's say I've declared UIViewController as a property in my class. In some cases we can implicitly assign UINavigationController to this property.
UIViewController *someNavigationControllerIn Objective-C I can simple assign
UIViewController *vc = self.someNavigationController; if (vc) { //then do something }As I understood in Swift I should do something like this if my self.centerViewController declared as UIViewController. Right
let nvc = self.centerViewController as! UINavigationControllerAlos how can I check
if nvc != nilIt says that it can't be nil.
最满意答案
as! UINavigationController 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 }as! UINavigationController means it's a forced downcast: it has been unwrapped, it's no longer an Optional, therefore it can't be nil anymore - and if it were nil (or not downcastable), it would have crashed the app.
You could use optional binding instead:
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 }更多推荐
发布评论