Last active
October 24, 2016 20:59
-
-
Save robertmryan/9f00acd8faec99b6da1c9300dddf7fdc to your computer and use it in GitHub Desktop.
Swift 2 example for user4806509 from http://stackoverflow.com/a/28755141/1271826
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Swift 2 | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
perform1 { | |
self.perform2 { | |
self.perform3 { | |
print("everything done") | |
} | |
} | |
} | |
} | |
func perform1(completionHandler: () -> Void) { | |
doSomethingAsynchronously() { | |
completionHandler() | |
} | |
} | |
func perform2(completionHandler: () -> Void) { | |
doSomethingElseAsynchronously() { | |
completionHandler() | |
} | |
} | |
func perform3(completionHandler: () -> Void) { | |
doSomethingCompletelyDifferentAsynchronously() { | |
completionHandler() | |
} | |
} | |
// clearly, you would do something more interesting than simply dispatching something after 4 seconds | |
func doSomethingAsynchronously(completionHandler: () -> Void) { | |
print("starting doSomethingAsynchronously") | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(4 * NSEC_PER_SEC)), dispatch_get_main_queue()) { | |
completionHandler() | |
print("finished doSomethingAsynchronously") | |
} | |
} | |
func doSomethingElseAsynchronously(completionHandler: () -> Void) { | |
print("starting doSomethingElseAsynchronously") | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(4 * NSEC_PER_SEC)), dispatch_get_main_queue()) { | |
completionHandler() | |
print("finished doSomethingElseAsynchronously") | |
} | |
} | |
func doSomethingCompletelyDifferentAsynchronously(completionHandler: () -> Void) { | |
print("starting doSomethingCompletelyDifferentAsynchronously") | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(4 * NSEC_PER_SEC)), dispatch_get_main_queue()) { | |
completionHandler() | |
print("finished doSomethingCompletelyDifferentAsynchronously") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I originally wrote this example, I assumed that, in
perform1
,perform2
, andperform3
, you wouldn't call your owndoSomething...
asynchronous methods, but rather call some some existing asynchronous API (e.g. geocode requests which shouldn't be run concurrently, network requests where each request is contingent upon the value retrieved by the prior request, etc.).This example, where we have trivial methods calling other trivial methods is somewhat contrived. Also, you'd generally be passing parameters into these various methods, as well as having the closures passing data back. But hopefully this illustrates the basic idea.