Reputation: 5
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?
Upvotes: 0
Views: 524
Reputation: 318774
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.
Upvotes: 7