Is this a bug with if-let when using filter and first?

Hey all.

I have been using Swift since the very first version, but this is the first time I find a situation like this.

I wrote a segment of code that uses filter and then first to search and grab an element from an array.

Consider the following code:

    let ids = ["id1", "id2", "id3"]
    let secondId = ids.filter { $0 == "id2" }.first

This compiles and does its job.

But when you add an if-let to this, it stops working:

        let ids = ["id1", "id2", "id3"]
        if let secondId = ids.filter { $0 == "id2" }.first {

Anonymous closure argument not contained in a closure.

I'm thinking it's having troubles distinguishing where each curly brace starts and when it ends. Adding a parenthesis to the curly braces of the filter solves this issue.

    let ids = ["id1", "id2", "id3"]
    if let secondId = ids.filter ({ $0 == "id2" }).first {
1 Like

The parentheses have always been necessary in this situation.

You would have the problem if you tried

if ids.filter { $0 == "id2" }.count > 0 {

Right, otherwise it's not clear which curly brace belongs to the if