Swift - Capture self in block is fixed
Do you remember issue of implicitly captured self in block and reference cycle in Objective-C?
// implicit self reference
^{
name = @"name";
};
// Fixed version
__weak typeof(self)weakSelf = self;
^{
__strong typeof(weakSelf)strongSelf = weakSelf;
strongSelf.name = @"name";
};
In swift this is fixed now. This is the code
{[unowned self] newName in
self.name = newName
}
- All reference to self in a closure must be explicit. You will see this compiler error -
reference to property 'name' in closure requires explicit 'self.' to make capture semantics explicit
- Capture list
We can declare what object should be weak or unowned in the closure. The syntax is
[ /*reference type*/ /*object*/, ... ]
Documentation about ARC and Resolving Strong reference cycle
You can find more in WWDC 2014 - Intermediate Swift