What the "self" refers to in closure - Swift -


i having hard time understanding happening in closure in swift , hoping me understand.

class myclass {      func printwhatever(words: string) {         print(words)     }      func dowhatever() {          dispatch_async(...) {                  //why self                     self.printwhatever("hello")         }     } } 

on line self.printwhatever("hello"), why have use self? xcode tells me have to, not sure why. so, question stored in closure. know closure captures surrounding context. how much? instance of myclass captured?

it's matter of clarity. time use method or property name without explicit recipient, implicitly being sent self. in anonymous function must make fact explicit. if say

printwhatever("hello") 

...you might not realize implicitly capturing self. might not realize that, if anonymous function itself stored somewhere in self, can wind dreaded retain cycle. therefore, compiler forces self explicitly, aware of implications of own actions.

the proof of there circumstances not have self in anonymous function. consider this:

func printwhatever(words: string) {     print(words) }  func dothis(f:()->()) {     f() }  func dowhatever() {     dothis {         self.printwhatever("hello") // self required     } } 

in above, must self, because compiler has no guarantee retain cycle might not happen. watch happens if add @noescape attribute:

func printwhatever(words: string) {     print(words) }  func dothis(@noescape f:()->()) { // *     f() }  func dowhatever() {     dothis {         printwhatever("hello") // ok!     } } 

the @noescape attribute guarantees passed function executed , not stored. self no longer required, because no retain cycle can take place.

personally, always self wherever allowed to, matter of style. , suggest same.


note: there language-change proposal rejected, , 1 of grounds rejection 1 give:

the requirement use self. within potentially-escaping closures useful indicator of potential retain cycles


Comments