Example
// Function with a completion handler parameter
func doWork(completion: @escaping (String) -> () ) {
DispatchQueue.global(qos: .userInitiated).async {
completion("Work is all done!")
}
}
// Function that calls your completion handler function
func startWork() {
print("Starting work")
doWork { (result) -> () in
print(result)
}
print("Waiting for doWork to finish.")
}
Console printout
Starting work Waiting for doWork to finish. Work is all done!
Quality of Service Parameter Enum
- userInteractive - Need it done almost instantaneously. Highest priority.
- userInitiated - Need it done in a few seconds or less.
- utility - Can wait a few seconds to a few minutes.
- background - Work will take significant time. Like minutes or hours. Lowest priority.
Notes
Closures all follow the same format:() -> ()For example, you see this format here:
doWork { (result) -> () in
But there are a few more ways you can write this:
doWork { (result) -> Void in
doWork { (result) in
doWork { (result: String) in
doWork() { result in
doWork { result in
These all work the same. The last one is probably the bare minimum you can get away with.(Swift 3)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.