Swift指针的相等性总是如此

时间:2015-02-23 10:14:47

标签: swift

在Swift中,以下if语句始终为true

if self.navigationController?.topViewController === self {
  // always enters the conditional block
}

如果我写这样的代码

if let c = self.navigationController?.topViewController {
  if c === self {
    // do stuff...
  }
}

它的行为符合预期。

我会假设第一个表达式首先尝试打开左侧,然后将其与self进行比较,但显然它没有。这是怎么回事?

1 个答案:

答案 0 :(得分:0)

据我所知,这取决于你检查这种情况的等级。如果您检查此条件

,则导航到特定的视图控制器
self.navigationController?.topViewController === self

总是如此。因为你在topViewController中。

但是如果你创建了另一个类的实例并在另一个类中检查并查找navigationController的topViewController,那么这可能会失败。

例如,Root viewcontroller是UINavigationController - > ViewController - > NextViewController

在ViewController.swift里面

 println(" \(self.navigationController?.topViewController === self)")
 // the above line prints "true" since I'm in a topViewController
 var nextVC =  NextViewController()
 println(" \(self.navigationController?.topViewController === nextVC)")
 // the above line prints "false" since nextVC instance is not topViewController of navigation controller.

因此,即使您使用

打开包装,重点也是如此
if let

它也只是永远进入自我阻止(如果(c === self){})。