简体   繁体   中英

Swift: Completion Closure never executes?

So basically, I'm trying to get back the string that the function foobar returns. Originally, I had tried just returning the string from foobar, but swift kept returning early/asynchronously? from foobar. Code below:

@IBAction func bAction(_ sender: UIButton) {
    print("this prints")
    foobar(completion: { (info) in
        print("this does not print")
    })
}

func foobar(completion: @escaping (_ info: String) -> ()) {
    var info = ""
    //insert code here
    print("this prints too")
    //insert more code here
}

What am I doing wrong?

Since you never call the completion handler, it isn't called.

You need to call completion("some string literal or string variable") from within your foobar method.

func foobar(completion: @escaping (_ info: String) -> ()) {
    var result = ""

    print("this prints too")

    completion(result)
}

But keep in mind that a completion handler is only useful when there is some asynchronous processing going on. If foobar doesn't do anything asynchronously then you should not be setting this up to use a completion handler. A simple return value is all you need.

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