简体   繁体   中英

Swift - how to implement completion handler with trailing closure?

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 ?

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
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM