"Cannot find 'input' in scope" when using trailing closure syntax

Hey guys!
I extracted this function and a call to it from page 143 into my playground, it’s almost exact except for the braces { } I added at the end of the function declaration.

func doAwesomeWork(on input: String,
                   using transformer: () -> Void,
                   then completion: () -> Void) {}

doAwesomeWork(on: "My Project") {
    print("Doing work on \(input) in `transformer`")
} then: {
    print("Finishing up in `completion`")
}

However the compiler throws the error Cannot find ‘input’ in scope for the function call when trying to interpolate the \(input) argument to the String within the first trailing closure.

I’m stuck trying to figure out why is this error happening, can someone help? Thanks!

You have to pass input to the first closure as an argument. You also need to have the function actually call the closures that are passed in, otherwise it won’t print anything.

func doAwesomeWork(on input: String,
                   using transformer: (String) -> Void,
                   then completion: () -> Void)
{
    transformer(input);
    completion();
}

doAwesomeWork(on: "My Project") {
    my_stuff in
    print("Doing work on \(my_stuff) in `transformer`")
} then: {
    print("Finishing up in `completion`")
}
2 Likes