unicorn_surprise
unicorn_surprise

Reputation: 1109

Ambiguous use of 'filter' after migration to Swift 4.2

am struggling to solve this small bug on the following extension on Dictionary. I realise there is a similar answer stating that declaring the variable type before returning it fixes it: Ambiguous use of 'filter' when converting project to Swift 4

However I'm not sure of the 'filter' type? Any help would be great. Cheers

func pick(_ keys: [Key]) -> Dictionary {
    return filter { (key: Key, _) -> Bool in
        keys.contains(key)
    }
}

Upvotes: 1

Views: 146

Answers (2)

JeremyP
JeremyP

Reputation: 86661

For dictionaries, the parameter to the filter closure is a tuple containing the key and the value. It always used to be that you couldn't separate the constituent parts of a tuple in the closure declaration and you had to split it yourself in the body.

You can try this:

func pick(_ keys: [Key]) -> Dictionary 
{
    return filter { (pair) -> Bool in
        let (key, _) = pair
        return keys.contains(key)
    }
}

Or even

func pick(_ keys: [Key]) -> Dictionary 
{
    return filter{ keys.contains($0.0)}
}

And you should delete your implementation of filter, Dictionary has one built in and that's likely the cause of the "ambiguous use" error.

Upvotes: 1

Sweeper
Sweeper

Reputation: 272725

You have added your own filter method to Dictionary, this is not necessary, as Swift already has such a method: filter.

This method seems to be added in Swift 4.2, which explains why you didn't get the error before. Since Swift has this method provided for you now, you can safely delete the filter that you wrote.

Upvotes: 1

Related Questions