2

Assuming a @nonescaping variadic closure parameter as in

func method(_ closures: () -> Void...)

then mutating it to @escaping as in

func method(_ closures: @escaping () -> Void...)

produces the following error.

@escaping attribute may only be used in function parameter position

  • 1
    https://stackoverflow.com/a/29750368/7880059 may be the answer. –  Jan 15 '18 at 16:51
  • `func method(_ closures: [@escaping () -> Void])` produces the same error as of Swift 4. –  Jan 15 '18 at 16:55
  • It’s a compiletime error. As far as I can see `@escaping` and `@autoclosure` are exclusively supported by the function type. _Edit: I was replying to Özgür Ersil’s now deleted comment._ –  Jan 15 '18 at 17:04

1 Answers1

4

You don't need to use @escaping here at all. Only a closure that is directly an argument (with nothing wrapping it) can be non-escaping.

A closure that is part of a variadic argument is (under the hood) wrapped in an Array, so it is already implicitly @escaping.

For example, this compiles and runs just fine:

class MyObject {

    var closures: [() -> ()] = []

    func add(_ closures: () -> () ...) {
        self.closures += closures
    }

    func run() {
        for closure in closures { closure() }
    }

}

let object = MyObject()
object.add({ print("first") }, { print("second") })
object.run()
rob mayoff
  • 375,296
  • 67
  • 796
  • 848