File tree 1 file changed +44
-13
lines changed
bk1ch02p058closureCapture/bk1ch02p058closureCapture
1 file changed +44
-13
lines changed Original file line number Diff line number Diff line change @@ -96,23 +96,54 @@ class ViewController: UIViewController {
96
96
97
97
// anonymous function version
98
98
99
- x = 0
100
- print ( x)
101
- pass100 { newX in
102
- x = newX
99
+ do {
100
+ var x = 0
101
+ print ( x)
102
+ pass100 { newX in
103
+ x = newX
104
+ }
105
+ print ( x)
103
106
}
104
- print ( x)
105
-
107
+
106
108
// anonymous function version with capture list
107
109
108
- x = 0
109
- print ( x)
110
- pass100 { [ x] newX in
111
- // x = newX // compile error
112
- var x = x
113
- x = newX // legal, but no effect on original x
110
+ do {
111
+ var x = 0
112
+ print ( x)
113
+ pass100 { [ x] newX in
114
+ // x = newX // compile error
115
+ var x = x
116
+ x = newX // legal, but no effect on original x
117
+ }
118
+ print ( x)
119
+ }
120
+
121
+ // yeah, but that isn't what I really wanted to prove
122
+ // let's try again
123
+
124
+ do {
125
+ var x = 0
126
+ let f : ( ) -> ( ) = {
127
+ print ( x)
128
+ }
129
+ f ( )
130
+ x = 1
131
+ f ( )
132
+ }
133
+
134
+ // but contrast:
135
+
136
+ do {
137
+ var x = 0
138
+ let f : ( ) -> ( ) = { [ x] in // *
139
+ print ( x)
140
+ // x = 100 // Cannot assign to value: 'x' is an immutable capture
141
+ }
142
+ // x = 100 // makes no difference either
143
+ f ( )
144
+ x = 1
145
+ f ( )
114
146
}
115
- print ( x)
116
147
117
148
118
149
func greet ( ) {
You can’t perform that action at this time.
0 commit comments