-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathclosures.swift
52 lines (36 loc) · 1.19 KB
/
closures.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import Foundation
// Closures have the syntax of:
/*
{ (parameters) -> return type in
body
}
*/
var numbers = [1, 2, 3, 4]
var reversed = numbers.sorted(by: {(a: Int, b: Int) -> Bool in
return a > b
})
// But type inference allows us to omit the types
// and write something more succinct...
reversed = numbers.sorted(by: { a, b in return a > b })
// ...And single-expression closures can even omit the return keyword.
reversed = numbers.sorted(by: { a, b in a > b })
// ...And even the param names can be omitted.
reversed = numbers.sorted(by: { $0 > $1 })
// ...But why stop there? Greater-than is an operator function!
reversed = numbers.sorted(by: >)
// Closures, of course, have the ability to access the variables
// in scope at the time the function is defined.
func sizeOfNumbers() -> Int {
return numbers.count
}
print(String(sizeOfNumbers())) // 4
numbers.append(5)
print(String(sizeOfNumbers())) // 5
// # Trailing Closures
// Similar to Ruby's blocks, if a function accepts a closure,
// you can specify it after the function's parens.
reversed = numbers.sort { $0 > $1 }
var toStringed = numbers.map {
(num: Int) -> String in
return String(num)
}