Swift — Closures

If you’re familiar with the concept of blocks in Objective-C, then you’ll get the idea of closures in Swift. Closures, like blocks, are an encapsulation of scope, essentially a function without the selector (method name).

"Closures are self-contained blocks of functionality that can be passed around and used in your code." - Apple iOS Developer Library

Here’s the format for a closure:

{(parameters) -> (return type) in
(perform actions here) }

Here’s an example:

let introduceMyself: (firstName: String, lastName: String) -> String = { (firstName: String, lastName: String) in
return "My name is \(firstName) \(lastName)" }

Closures are especially useful when escaping an asynchronous call, say to an API. The closure allows the operation that the data is needed for to be continued once the data is returned. Passing closures can make your code more versatile and less error prone. The closure means that you can abstract the method calls out into another file, while still having the resulting implementation occur where you would like. Here’s an example:

func asyncAPIRequest(completion: (json: [String: Anyobject]) -> Void   
) {
//Async call is returned in here, say a variable called "response"
if let dict = response as? [String: Anyobject] {
completion(json: dict)

Meanwhile, say in your tableview controller, you define what you’d like to do with the json.

      (json: Dictionary<String, AnyObject>) in
       print json
Show your support

Clapping shows how much you appreciated Varindra Hart’s story.