swiftclosures

Swift Closure Capture List without the "in" keyword


does anybody know where this is documented? All the places I searched for, closures require a in keyword after the capture list but there is a valid case in which you can just specify the capture list. I guess this is the default behaviour of the closure made explicit.

var greeting = "Hello, playground"

let closure = { [greeting]
     print(greeting) 
}

Solution

  • The in keyword is required if you want to have a capture list. Don't ignore the compiler warnings!

    warning: expression of type '[String]' is unused
    let closure = { [greeting]
                    ^~~~~~~~~~
    

    It's telling you that this [greeting] is being understood as a [String] (i.e. Array<String>). So this is a single-element array literal that's being unused, as if you had written:

    let closure = {
        [greeting] // Unused Array!
        print(greeting)
    }
    

    You need the in so that this syntax is treated as a capture list, instead.