Swift 5.7 - `if let` works on non-optionals inside closures

Viewed 93

As far as I know, you can't use if let on variables that aren't optional...

func run() {
    let title = "Hello, world!"
    if let title = title { /// Initializer for conditional binding must have Optional type, not 'String'
        print(title)
    }
}

... but for some reason, when it's inside a closure, it works:

func run() {
    let title = "Hello, world!"
    let closure = {
        if let title = title { /// No error!
            print(title)
        }
    }
    closure()
}

This was on Xcode 14.0 beta (14A5228q). Is this a bug, or a feature? When I tested on Xcode 13.3 (13E113), the error appeared again.


On a side note, the following SwiftUI code compiles fine on both Xcode 13 and Xcode 14:

struct ContentView: View {
    let title = "Hello, world!"

    var body: some View {
        VStack {
            if let title = title { /// Works fine!
                Text(title)
            }
        }
    }
}

And it's not just VStack — anything marked @ViewBuilder seems to work.

struct ContentView: View {
    let title = "Hello, world!"

    var body: some View {
        ContainerView {
            if let title = title { /// works fine!
                Text(title)
            }
        }
    }
}

struct ContainerView<Content: View>: View {
    @ViewBuilder var content: Content
    var body: some View {
        content
    }
}

"Hello, world!" displayed

Is this a documented feature, or a bug?

0 Answers
Related