-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapturing values
65 lines (44 loc) · 1.7 KB
/
capturing values
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
53
54
55
56
57
58
59
60
61
62
63
64
func doIncrement(data: Int) -> () -> Int{
var total = 0
func incrementer() -> Int // don't have paramenters but capturing value
{
total += data
return total
}
return incrementer
}
var incrementByFive = doIncrement(data: 5)
print("incremented value is: ", incrementByFive())
print(incrementByFive())
print(incrementByFive())
// functions and closures are reference types
let alsoIncrementByFive = incrementByFive
print("still incremented by reference: ",alsoIncrementByFive())
//
func printMessage(name: String, newClosure: () -> () ){
print("hello")
newClosure()
print("function ended")
}
printMessage(name: "rohit",newClosure: { print("rohit") })
// @escaping closures
var completionHandlers: [() -> Void] = []
func completionHandlerEscaping(completionHandler: @escaping () -> Void){
completionHandlers.append(completionHandler)
}
// autoclosure
// var customerLine = ["mr. gold", "luise", "anna", "ada"]
// func printCustomer(customer setClosur: () -> (String) ){
// print("\nnow it's \(setClosur())'s turn")
// }
// printCustomer(customer: { customerLine.remove(at: 1) })
// print(customerLine.count)
var customerLine = ["mr. gold", "luise", "anna", "ada"]
// The argument is automatically converted to a closure, because the setCustomer parameter’s type is marked with the @autoclosure attribute
func printCustomer(customer setCustomer: @autoclosure () -> (String) ){
print("\nnow it's \(setCustomer())'s turn")
}
printCustomer(customer: customerLine.remove(at: 1) )
print(customerLine.count)
// Note
// Overusing autoclosures can make your code hard to understand. The context and function name should make it clear that evaluation is being deferred.