swiftguard-statement

expected expression in conditional


I have written the following function and am getting the following error in the guard statement.

expected expression in conditional

func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool {

    // form a dictionary key is the number, value is the index
    var numDict = [Int : Int]()
    for (i,num) in nums.enumerated()
    {
        guard let index = numDict[num] , where i - index <= k else
        {
            numDict [num] = i
            continue
        }
        return true
    }

    return false

}

Solution

  • The where keyword adds another expression to the first expression of the actual guard statement. Instead you can separate both expressions by a comma and remove the where keyword.

    Why is that?

    In Swift you can enumerate multiple expressions separated by commas in one if or guard statement like so:

    if a == b, c == d {}
    guard a == b, c == d else {}
    

    This is similar to the && operator. The difference is that the comma version allows unwrapping of optionals like so:

    if let nonOptional = optional, let anotherNonOptional = anotherOptional {}
    guard let nonOptional = optional, let anotherNonOptional = anotherOptional else {}
    

    Why is the Internet showing code samples where if and guard are used together with where?

    That's because in older Swift versions it was possible to use where together with if and guard. But then this was removed because where was meant to add an expression to a non-expression statement like for-in or as a constraint for class and struct definitions.