0

Suppose I have function that does some stuff

func doSomethingAwesome(completion:(success:Bool) -> Bool) {

//some stuff

}

How can I transform it to trailing closure ? How can I transform control from body of function to completion block ?

2
  • 2
    I don't quite understand your question. What you're showing is a function implementation that takes a closure parameter. "Trailing closure syntax" is a shorthand notation that applies to the invocation of the function. This function can be invoked using trailing closure syntax. Beyond that, I'm not sure what you're asking Commented Jun 20, 2016 at 12:37
  • 2
    Reminder: stackoverflow.com/a/33020097/2227743 Commented Jun 20, 2016 at 12:41

2 Answers 2

1

It is already trailing closure. You can call completion in body:

func doSomethingAwesome(completion:(success:Bool) -> Bool) {

    //some stuff
    let result = completion(success: true)
}

And thats how you can use trailing closure syntax calling this func:

doSomethingAwesome {
        success in
        return success
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You can just call that function (which already has a trailing closure) by doing:

doSomethingAwesome{ finished in

    if finished{
          return true
    }
return false
}

Your completion handler is of type Bool. So Bool is used as I showed here.

4 Comments

Your code will not compile: you passed Bool -> Void closure.
Edited. Thanks! :)
will not compile again =) you used unresolved identifiers, use true/false instead
Done! Thanks! Again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.