Home > Blockchain >  How to pass argument to multiple trailing closures?
How to pass argument to multiple trailing closures?

Time:12-25

I want to print "voala" within both closures, however it gets error: Cannot find 'sound' in scope. I found similar example in book, however it does not work, therefore asking.

func multipleTrailing(scream sound: String, first closure1: () -> Void, second closure2: () -> Void) {
    closure1()
    closure2()
    }

multipleTrailing(scream: "voala") {
    print("\(sound), calling from closure1, omitting argument label \"first\"")
        } second: {
    print("\(sound), calling from closure2, keeping argument label \"second\"")
        }

CodePudding user response:

You should give the value to the closures. Here both closures have an input parameter of a String type, and the multipleTrailing function gives the sound parameter to both of them. On the caller site this parameter can have any name (here I gave them sound in both places), and you can access those values

func multipleTrailing(scream sound: String, first closure1: (String) -> Void, second closure2: (String) -> Void) {
    closure1(sound)
    closure2(sound)
}

multipleTrailing(scream: "voala") { sound in
    print("\(sound), calling from closure1, omitting argument label \"first\"")
} second: { sound in
    print("\(sound), calling from closure2, keeping argument label \"second\"")
}
  • Related