It is a bit complicated for myself to read documentation about capturing lists and closures.
For example, neither Closures nor capturing lists sections contains a capturing list with assignment.
Consider following complex example and answer one question: What will be printed to console?
enum ClosuresScope {
class ExampleClass: CustomStringConvertible {
var item: Int = 0
func update(item: Int) {
self.item += item
}
var description: String {
return "self -> \(self.item)"
}
}
struct ExampleStruct {
var item: Int = 0
mutating func update(item: Int) {
self.item += item
}
}
class CapturingAndBlockAttribute {
func example() {
let classItem = ExampleClass()
var structItem = ExampleStruct()
let closure: () -> (Int) = {
[unowned internalClass = classItem, internalStruct = structItem] in
classItem.update(item: 3)
internalClass.update(item: 20)
internalStruct.update(item: 5)
structItem.update(item: 10)
return classItem.item
}
classItem.update(item: 5)
structItem.update(item: 5)
_ = closure()
print("classItem: \(classItem) structItem: \(structItem)")
}
}
}