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
}
The
where
keyword adds another expression to the first expression of the actualguard
statement. Instead you can separate both expressions by a comma and remove thewhere
keyword.Why is that?
In Swift you can enumerate multiple expressions separated by commas in one
if
orguard
statement like so:This is similar to the
&&
operator. The difference is that the comma version allows unwrapping of optionals like so:Why is the Internet showing code samples where
if
andguard
are used together withwhere
?That's because in older Swift versions it was possible to use
where
together withif
andguard
. But then this was removed becausewhere
was meant to add an expression to a non-expression statement likefor-in
or as a constraint forclass
andstruct
definitions.