Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

swift3 - How do you write a completion handler in Swift 3?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...