Quotation of the week:
the lack of explicit signalling required is a potential footgun.
shared/__blockwould help but I wonder if something at the point of use/capture would be even better (similar to explicitselfin a closure).
I thought of reasons why that might be better (e.g. [shared store] in the capture list) before my coffee but now I can't retrieve them.
Why do you think so?
Downsides:
- When there are multiple closures in the function body, the variable is boxed once per declaration site, not once per closure. Not sure what it would mean to notate it just one of two closures.
- That's a lot of syntactic weight to add to the closure, especially xN closures.
Of course I'd also like all global and static vars to be marked shared (0.5 x
).
Yes, good point any access causes the change, thanks for asking.
You can of course do that with by explicitly capturing the variable, which creates a distinct copy, but then of course the value is not shared with the function body:
DispatchQueue.global().async { [store] in // <=== HERE
for _ in 1...iterations {
_ = store
}
}
or, simplified:
var store = 0
let f = { [store] in store }
store += 1
print(f()) // prints 0
If you actually want to share and mutate the value across concurrent computations, as others have pointed out, you need synchronization.