Search code examples
swiftmkannotationguard

Guard statement with two conditions in Swift


My understanding is that having two conditions in a guard statement separated by a comma functions imposes the requirement that they both be true. I can write a guard statement with either one independently and the code compiles but when I combine them with a comma, it gives an error. Is there anything wrong with my syntax or can anyone explain why it fails to compile?

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'

}

Solution

  • You are using too many pointless parentheses, basically don't use parentheses in if and guard statements in simple expressions.

    The error occurs because the compiler treats the enclosing parentheses as tuple ((Bool, Bool)), that's what the error message says.

    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 {