如何在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...我目前使用的是Xcode6-Beta7。
发布于 2014-09-04 23:15:48
您的代码无法编译。nil只能出现在可选选项中。您需要使用optional,var view: UIView? = self.superview来声明view。然后将它与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
}或者执行let绑定,但我认为在这里似乎没有必要。
发布于 2014-09-04 22:41:16
while的语法允许可选绑定。使用:
var view: UIView = self
while let sv = view.superview {
count += 1
view = sv
}感谢@ben-leggiero指出view不必是Optional (就像问题本身一样),并指出了Swift 3的不兼容性
https://stackoverflow.com/questions/25667021
复制相似问题