Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is self captured within a nested function

With closures I usually append [weak self] onto my capture list and then do a null check on self:

func myInstanceMethod() {     let myClosure =     {        [weak self] (result : Bool) in        if let this = self        {             this.anotherInstanceMethod()        }     }         functionExpectingClosure(myClosure) } 

How do I perform the null check on self if I'm using a nested function in lieu of a closure (or is the check even necessary...or is it even good practice to use a nested function like this) i.e.

func myInstanceMethod() {     func nestedFunction(result : Bool)     {         anotherInstanceMethod()     }      functionExpectingClosure(nestedFunction) } 
like image 391
Jaja Harris Avatar asked Oct 30 '14 23:10

Jaja Harris


People also ask

What is an example of a nested function?

Users typically create nested functions as part of a conditional formula. For example, IF(AVERAGE(B2:B10)>100,SUM(C2:G10),0). The AVERAGE and SUM functions are nested within the IF function.

What is the meaning of nested function?

Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators.

Can we nest functions within functions?

Any function in a program file can include a nested function. The primary difference between nested functions and other types of functions is that they can access and modify variables that are defined in their parent functions.


1 Answers

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) } 
like image 156
rintaro Avatar answered Sep 19 '22 06:09

rintaro