user500 user500 - 15 days ago 9
Swift Question

How to check for `nil` in while loop condition in Swift?

How to check for

nil
in while loop in Swift? I'm getting error on this:

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.

Answer

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.

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.

Comments