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

时间:2021-02-23 10:23:50

How to check for nil in while loop in Swift? I'm getting error on this:

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

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...

I'm currently using Xcode6-Beta7.

我目前正在使用Xcode6-Beta7。

2 个解决方案

#1


0  

Your code cannot compile. nil can only appear in optionals. You need to declare view with optional, var view: UIView? = self.superview. Then compare it with nil in the while-loop.

你的代码无法编译。 nil只能出现在期权中。您需要使用可选的var视图声明视图:UIView? = self.superview。然后将它与while循环中的nil进行比较。

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
}

Or do a let binding, But it seems not necessary here, I think.

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

#2


58  

The syntax of while allows for optional binding. Use:

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

var view: UIView = self
while let sv = view.superview {
  count += 1
  view = sv
}

[Thanks to @ben-leggiero for noting that view need not be Optional (as in the question itself) and for noting Swift 3 incompatibilities]

[感谢@ ben-leggiero注意到该视图不必是可选的(如问题本身)和注意Swift 3不兼容性]

#1


0  

Your code cannot compile. nil can only appear in optionals. You need to declare view with optional, var view: UIView? = self.superview. Then compare it with nil in the while-loop.

你的代码无法编译。 nil只能出现在期权中。您需要使用可选的var视图声明视图:UIView? = self.superview。然后将它与while循环中的nil进行比较。

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
}

Or do a let binding, But it seems not necessary here, I think.

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

#2


58  

The syntax of while allows for optional binding. Use:

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

var view: UIView = self
while let sv = view.superview {
  count += 1
  view = sv
}

[Thanks to @ben-leggiero for noting that view need not be Optional (as in the question itself) and for noting Swift 3 incompatibilities]

[感谢@ ben-leggiero注意到该视图不必是可选的(如问题本身)和注意Swift 3不兼容性]