Tutorial by Examples

Closures (also known as blocks or lambdas) are pieces of code which can be stored and passed around within your program. let sayHi = { print("Hello") } // The type of sayHi is "() -> ()", aka "() -> Void" sayHi() // prints "Hello" Like other fun...
The basic closure syntax is { [capture list] (parameters) throws-ness -> return type in body }. Many of these parts can be omitted, so there are several equivalent ways to write simple closures: let addOne = { [] (x: Int) -> Int in return x + 1 } let addOne = { [] (x: Int) -> Int in...
Functions may accept closures (or other functions) as parameters: func foo(value: Double, block: () -> Void) { ... } func foo(value: Double, block: Int -> Int) { ... } func foo(value: Double, block: (Int, Int) -> String) { ... } Trailing closure syntax If a function's last parameter ...
class MyClass { func sayHi() { print("Hello") } deinit { print("Goodbye") } } When a closure captures a reference type (a class instance), it holds a strong reference by default: let closure: () -> Void do { let obj = MyClass() // Captures a strong re...
Closures are often used for asynchronous tasks, for example when fetching data from a website. 3.0 func getData(urlString: String, callback: (result: NSData?) -> Void) { // Turn the URL string into an NSURLRequest. guard let url = NSURL(string: urlString) else { return } let re...
A closure can be defined with a typealias. This provides a convenient type placeholder if the same closure signature is used in multiple places. For example, common network request callbacks or user interface event handlers make great candidates for being "named" with a type alias. public...

Page 1 of 1