Basically async is you asking someone else to ex. go shop groceries for you so you can continue with your programming and when he gets back from the store you receive the groceries and puts it in the refrigerator.
Practical example:
// Correct way of implementing
asyncShopGrocieries(["Milk", "Cookies", "Potatoes"]) { groceries in
fridge.insert(groceries)
}
// Incorrect way of implementing
var groceries:[String]! // You create a variable
asyncShopGrocieries(["Milk", "Cookies", "Potatoes"]) // You make an async request
{ groceries in // Block that handles the data when done
groceries = groceries_
} // Block will execute after you reach the end of this function
fridge.insert(groceries) // When you come here you will try to put the groceries inside the fridge while he is still on his way TO the store.
UPDATE
class SomeClass {
var groceries:[String]?
var groceries2:[String]?
var fridge = Fridge()
func gotAllGroceries(groc: [String], groc2: [String]) {
fridge.insert(self.groc, groc2)
}
func getGroceries() {
asyncShopGrocieries(["Milk", "Cookies", "Potatoes"]) { groceries in
self.groceries = groceries
if groceries2 != nil {
self.gotAllGroceries(self.groceries!, groc2: self.groceries2!)
}
}
asyncShopGrocieries(["Candy", "Steak", "Apples"]) { groceries in
self.groceries2 = groceries
if groceries != nil {
self.gotAllGroceries(self.groceries!, groc2: self.groceries2!)
}
}
}
}
UPDATE 2
func async(time: UInt32, action: ()->()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
sleep(time)
action()
}
}
func testDispatchGroup() {
let group = dispatch_group_create()
let startDate = NSDate()
dispatch_group_enter(group)
async(2) {
println("1 done")
dispatch_group_leave(group)
}
dispatch_group_enter(group)
async(1) {
println("2 done")
dispatch_group_leave(group)
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
println("Everything done!")
println("Total time: \(NSDate().timeIntervalSinceDate(startDate))")
}
}
Prints out:
2 done
1 done
Everything done!
Total time: 2.00842797756195