guard 语句中的多个 let 是否与单个 let 相同?

Are multiple lets in a guard statement the same as a single let?

在功能上有区别吗:

guard let foo = bar, let qux = taco else { 
  ...
}

并且:

guard let foo = bar, qux = taco else {
  ...
}

在我看来它们是一样的,不需要额外的 let

不,在 Swift 3.0 中已经不一样了。 Xcode 给你一个错误,并要求你在应用多个变量时添加 let

所以你应该使用

guard let foo = bar, let qux = taco else { 
  ...
}

这些在Swift3中是不同的。在这种情况下:

guard let foo = bar, let qux = taco else { 

你是说 "optional-unwrap bar into foo. If successful, optional unwrap taco into qux. If successful continue. Else ..."

另一方面:

guard let foo = bar, qux = taco else {

说 "optional-unwrap bar into foo. As a Boolean, evaluate the assignement statement qux = taco" 因为赋值语句不 return Swift 中的布尔值,这是一个语法错误。

此更改允许更灵活的 guard 语句,因为您可以在整个链中混合使用可选的展开和布尔值。在 Swift 2.2 中,您必须展开所有内容,然后在 where 子句的末尾进行所有布尔检查(有时无法表达条件)。