Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 349
user500 Avatar asked Sep 04 '14 13:09

user500


People also ask

How do you check if something is nil Swift?

In Swift, if we define a variable to be an optional variable, in that case, this variable can have no value at all. If optional variable is assigned with nil , then this says that there is no value in this variable. To check if this variable is not nil, we can use Swift Inequality Operator != .

Is nil a value in Swift?

In Swift: nil is not a pointer, it's the absence of a value of a certain type. NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed.

How does while loop work in Swift?

Swift while LoopA while loop evaluates condition inside the parenthesis () . If condition evaluates to true , the code inside the while loop is executed. condition is evaluated again. This process continues until the condition is false .

How do you end a while loop in Swift?

You can exit a loop at any time using the break keyword. To try this out, let's start with a regular while loop that counts down for a rocket launch: var countDown = 10 while countDown >= 0 { print(countDown) countDown -= 1 } print("Blast off!")


2 Answers

The syntax of while allows for optional binding. Use:

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]

like image 190
GoZoner Avatar answered Sep 20 '22 20:09

GoZoner


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.

like image 45
Windor C Avatar answered Sep 18 '22 20:09

Windor C