Swift 警卫任务

Swift 警卫任务,swift,Swift,这是密码 func howMany() -> Int { return 10 } func Call() -> Void { guard case let output = howMany(), output > 5 else { return } } Call() 我真的不明白警卫箱是怎么工作的。这看起来很像一个模式匹配条件,我们比较howmount()的结果是否等于output,如果等于,则将值分配给output,然后将其与文本值5进行比较。然而,当我删除

这是密码

func howMany() -> Int {
   return 10
}

func Call() -> Void {
   guard case let output = howMany(), output > 5 else { return }
}

Call()
我真的不明白警卫箱是怎么工作的。这看起来很像一个模式匹配条件,我们比较howmount()的结果是否等于output,如果等于,则将值分配给output,然后将其与文本值5进行比较。然而,当我删除输出>5的行时,编译器说,“保护条件始终为真,主体不可访问。”

根据模式,如果我们将其转换为switch语句,它看起来非常像

switch howMany() {
   case let output where output > 5:
      break;
}
问题是,如果它可以直接转换为switch语句,那么当我们删除where条件时,就不应该出现警告“保护条件始终为true,body不可访问”

我希望有人能对此有所了解。

考虑一下:

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")
}
你得到了警告:

“守卫”条件始终为真,身体无法到达

这个警告是正确的,因为尸体是无法到达的

如果您在
开关
示例中执行等效操作:

func bar() {
    switch howMany() {
    case let output:
        print("\(output) is greater than 5")

    default:
        print("less than or equal to 5")
        return
    }
}
如果您这样做,您将收到类似的警告:

默认值永远不会被执行

而且,这也是有道理的,因为不会达到
默认值

现在,考虑你的例子<代码>开关< /> >没有<代码>默认子句:

func bar() {
    switch howMany() {
    case let output:
        print("output:", output)
    }
}

您不会在此处收到警告,只是因为没有
default
子句(与
guard
语句的“body”类似)。

在保护条件下使用case允许您使用非可选的值赋值。顺便说一句,考虑到您正在从方法返回一个常量,该警告是正确的。如果不需要条件,只需使用
让output=howmounty()
。请注意,以小写字母开头命名方法是Swift命名约定。您指的是什么条件?除了where子句作为条件外,我看不到该条件。我仍然不明白。条件语句中的逗号(
)基本上意味着
和/&&
——但它们是一次计算一次的。这允许您创建变量
output
,然后将其与
5
进行比较-否则,编译器会说
“output”
不存在。