Skip to content

Commit bee7062

Browse files
committed
better capture list example
1 parent 793c077 commit bee7062

File tree

1 file changed

+44
-13
lines changed

1 file changed

+44
-13
lines changed

bk1ch02p058closureCapture/bk1ch02p058closureCapture/ViewController.swift

+44-13
Original file line numberDiff line numberDiff line change
@@ -96,23 +96,54 @@ class ViewController: UIViewController {
9696

9797
// anonymous function version
9898

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)
103106
}
104-
print(x)
105-
107+
106108
// anonymous function version with capture list
107109

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()
114146
}
115-
print(x)
116147

117148

118149
func greet () {

0 commit comments

Comments
 (0)