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

前端 未结 2 1944
心在旅途
心在旅途 2021-02-05 04:42

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 { /         


        
相关标签:
2条回答
  • 2021-02-05 05:16

    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]

    0 讨论(0)
  • 2021-02-05 05:26

    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.

    0 讨论(0)
提交回复
热议问题