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
wherekeyword adds another expression to the first expression of the actualguardstatement. Instead you can separate both expressions by a comma and remove thewherekeyword.Why is that?
In Swift you can enumerate multiple expressions separated by commas in one
iforguardstatement 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
ifandguardare used together withwhere?That's because in older Swift versions it was possible to use
wheretogether withifandguard. But then this was removed becausewherewas meant to add an expression to a non-expression statement likefor-inor as a constraint forclassandstructdefinitions.