With closures I usually append [weak self]
onto my capture list and then do a null check on self:
func myInstanceMethod()
{
let myClosure =
Does not seem to be the case anymore. This is valid in swift 4.1:
class Foo {
var increment = 0
func bar() {
func method1() {
DispatchQueue.main.async(execute: {
method2()
})
}
func method2() {
otherMethod()
increment += 1
}
method1()
}
func otherMethod() {
}
}
The question remains: How is self
captured ?
Unfortunately, only Closures have "Capture List" feature like [weak self]
. For nested functions, You have to use normal weak
or unowned
variables.
func myInstanceMethod() {
weak var _self = self
func nestedFunction(result : Bool) {
_self?.anotherInstanceMethod()
}
functionExpectingClosure(nestedFunction)
}
I use this template
class A{
func foo(){
func bar(_ this:A){
this.some();
}
bar(self);
}
func some(){
}
}