Swift 中有两个条件的 Guard 语句

Guard statement with two conditions in Swift

我的理解是,在 guard 语句中使用逗号函数分隔的两个条件强加了它们都为真的要求。我可以独立地编写一个保护语句,代码可以编译,但是当我将它们与逗号组合时,它会出错。我的语法有什么问题吗?或者谁能解释为什么编译失败?

guard (mode != "mapme") else {  //compiles
}

guard (!annotation is MKUserLocation) else { //compiles
}

guard (mode != "mapme",!(annotation is MKUserLocation)) else { //gives error:'(Bool, Bool)' is not convertible to 'Bool'

}

你使用了太多无意义的括号,基本上不要在 ifguard 语句中使用括号 简单 表达式。

错误发生是因为编译器将括起来的括号视为元组 ((Bool, Bool)),这就是错误消息所说的。

guard mode != "mapme" else {

guard !(annotation is MKUserLocation) else { // here the parentheses are useful but the `!` must be outside of the expression

guard mode != "mapme", !(annotation is MKUserLocation) else {

在 swift 中,if 语句、for 循环等不需要外括号。通常认为不包含它们是好的做法,在您的情况下,当您包含括号时,保护语句变成一个元组。因此,只需将您的代码更改为此,它就可以正常工作了。

guard mode != "mapme" else {  //compiles
}

guard !(annotation is MKUserLocation) else { //compiles
}

guard mode != "mapme", !(annotation is MKUserLocation) else { 

}

如果您想使用括号,只需使用 && 运算符(或 || 如果您想要 OR 子句)

guard (mode != "mapme" && !(annotation is MKUserLocation)) else {