Use of capture lists in structs

You're running up against the behavior that is noted in this post as a potential gotcha. Namely, when you put a variable in a capture list, you are effectively capturing the referenced variable by value, whereas without the capture list you are capturing by reference.

The reason this isn't exhibited by capturing self is that when you modify myStruct by setting myStruct.a = 99, you have actually formed a new SomeStruct instance, which is now different from the instance that is captured in innerClosure or innerClosureWithExplicitCapture. Consider the simpler example:

struct S {
  var x: Int
  func printX() { print(x) }
}

var s = S(x: 0)
let printXOuter = s.printX

s.x = 3

printXOuter() // 0
s.printX() // 3

Here, even though there's no closures involved, we still see that the changes to s don't propagate to printXOuter.

3 Likes