swift - Why is self in closure not referring to the owning class instance? -


in code below, print statement outputs "c2", class creating closure being passed init argument c1.

class c1 {     let closure: () -> void     init(closure: @escaping () -> void) {         self.closure = closure     } }  class c2 {     func test() {         let c1 = c1(closure: { [unowned self] in             // expect "self" c1 instance             print(type(of:self))         })         c1.closure()     } } c2().test() 

i expecting "self" c1 instance. why not that?

consider expectation if wrote code this:

class c2 {     func test() {         let closure = { [unowned self] in             print(type(of:self))         })         let c1 = c1(closure: closure)         c1.closure()     } } 

they doing same thing, version compresses 1 line. still creating closure parameter within scope of test() method of type c2. though have in on single line, closure parameter must still created , exist in scope of test() method before c1 ever instantiated it.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -