如何在Swift中检查while循环条件中的`nil`?

use*_*500 22 swift

如何nil在Swift中检查while循环?我收到错误:

var count: UInt = 0
var view: UIView = self
while view.superview != nil { // Cannot invoke '!=' with an argument list of type '(@lvalue UIView, NilLiteralConvertible)'
    count++
    view = view.superview
}
// Here comes count...
Run Code Online (Sandbox Code Playgroud)

我目前正在使用Xcode6-Beta7.

GoZ*_*ner 74

while允许可选绑定的语法.使用:

var view: UIView = self
while let sv = view.superview {
  count += 1
  view = sv
}
Run Code Online (Sandbox Code Playgroud)

[感谢@ ben-leggiero注意到view不需要Optional(如问题本身)和注意Swift 3不兼容性]


Win*_*r C 1

您的代码无法编译。nil只能出现在选项中。您需要view使用可选的 来声明var view: UIView? = self.superviewnil然后与while 循环中进行比较。

var count: UInt = 0
var view: UIView? = self.superview
while view != nil { // Cannot invoke '!=' with an argument list of type '(@lvalue UIView, NilLiteralConvertible)'
    count++
    view = view!.superview
}
Run Code Online (Sandbox Code Playgroud)

或者做一个let绑定,但我认为这里似乎没有必要。

  • “nil 只能出现在可选项中。” 或任何符合“NilLiteralConvertible”的类型 (3认同)