嗯......这是代码
func howMany() -> Int {
return 10
}
func Call() -> Void {
guard case let output = howMany(), output > 5 else { return }
}
Call()
我真的不明白警卫案是如何运作的。这看起来非常像模式匹配条件,我们比较howMany()的结果是否等于输出,如果是,则将值赋给输出,然后将其与文字值5进行比较。但是,当我删除该行时输出> 5,编译器说,“保护条件总是正确的,身体是不可达的。”
根据模式,如果我们将它转换为switch语句,它看起来非常像这样
switch howMany() {
case let output where output > 5:
break;
}
问题是它是否可以直接转换为switch语句,那么当我们删除where条件时,不应该出现“保护条件总是正确,正文无法访问”的警告。
我希望有人能够对此有所了解。
考虑:
func foo() {
guard case let output = howMany(), output > 5 else {
print("less than or equal to 5")
return
}
print("\(output) is greater than 5")
}
这大致相当于:
func bar() {
switch howMany() {
case let output where output > 5:
print("\(output) is greater than 5")
default:
print("less than or equal to 5")
return
}
}
如果你删除> 5
标准:
func foo() {
guard case let output = howMany() else {
print("less than or equal to 5")
return
}
print("\(output) is greater than 5")
}
你得到警告:
'守卫'条件永远是真实的,身体是无法到达的
这个警告是正确的,因为身体是无法到达的。
如果你在switch
例子中做了相同的事情:
func bar() {
switch howMany() {
case let output:
print("\(output) is greater than 5")
default:
print("less than or equal to 5")
return
}
}
如果您这样做,您将收到类似的警告:
默认永远不会被执行
而且,它是有道理的,因为default
将无法到达。
现在,考虑一下没有switch
子句的示例default
:
func bar() {
switch howMany() {
case let output:
print("output:", output)
}
}
你没有在这里收到警告只是因为没有default
条款(类似于guard
声明的“正文”)。