I have followed a tutorial on Swift completion handlers to write this function. Whenever I attempt to use the closure, I receive an error, "Expression resolves to an unused function"
func completion<Result>(onResult: @escaping (Result) -> Void,
onError: @escaping (Error) -> Void) -> ((Result?, Error?) -> Void) {
return { (maybeResult, maybeError) in
if let result = maybeResult {
onResult(result)
} else if let error = maybeError {
onError(error)
} else {
onError(SplitError.NoResultFound)
}
}
}
How it's being called
completion(onResult: { (j) in
print(j)
}) { (e) in
print(e)
}
error: Expression resolves to an unused function
The generic function completion
returns a closure which is intended to use as completion handler to some async functions.
For example, assume you have some async method like this:
func someAsyncFunc(completion: @escaping (Data?, Error?)->Void) {
//...
}
So, to use the closure, you may need to store the returned closure to some closure variable and use it later:
let myCompletionHandler = completion(onResult: { (j: Data) in
print(j)
}) { (e) in
print(e)
}
someAsyncFunc(completion: myCompletionHandler)
Or else, you can write it directly as a parameter:
someAsyncFunc(completion: completion(onResult: { (j) in
print(j)
}) { (e) in
print(e)
})
Anyway, I cannot be sure if this might really be an improvement and you should better find a better tutorial.
That looks ok to me, you can always try
completion(onResult: { (j) in print(j)},
onError: { (e) in print(e) })
Your function returns a closure. What you haven't done is used the closure. Do this:
completion(onResult: { (j) in
print(j)
}) { (e) in
print(e)
}()
Note the parenthesis at the end. Or to be more clear:
let completionClosure = completion(onResult: { (j) in
print(j)
}) { (e) in
print(e)
}
completionClosure()
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.