Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a completion handler in Swift 3?

Tags:

swift

swift3

I was wondering how to make a completion handler for a function I'm creating in Swift 3. This is how I did my function right before I updated to Swift 3:

func Logout(completionHandler: (success: Bool) -> ()) {
    backendless.userService.logout(
        { ( user : AnyObject!) -> () in
            print("User logged out.")
            completionHandler(success: true)
        },
        error: { ( fault : Fault!) -> () in
            print("Server reported an error: \(fault)")
            completionHandler(success: false)
    })}

But now I can't figure out the best approach that works right now.

like image 889
Noah G. Avatar asked Sep 22 '16 15:09

Noah G.


People also ask

What is completion block in Swift?

Swift Closures with Completion handler Closures are self-contained blocks of functionality that can be passed around and used in your code. Said differently, a closure is a block of code that you can assign to a variable. You can then pass it around in your code, for instance to another function. … 7 min read.

What is difference between closure and completion handler Swift?

As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn't called until the operation is completed—the closure needs to escape, to be called later.


1 Answers

In Swift 3 the function parameter labels in closures are gone.

Remove all occurrences of success: and add @escaping

func Logout(completionHandler:@escaping (Bool) -> ()) {
    backendless?.userService.logout(
        { user in
            print("User logged out.")
            completionHandler(true)
        },
        error: { fault in
            print("Server reported an error: \(fault)")
            completionHandler(false)
    })
}

And use it

Logout() { success in
   print(success)
}
like image 60
vadian Avatar answered Nov 13 '22 14:11

vadian