Can capture uninitialized instance into closure

I have a code like this:

class A {
   var a: Int
   var clos: () -> () = { [unowned self] in
      self.a
   }
   init(...)
}

Unfortunately, it doesn't compile because it says self is not initialized fully. How would you solve this case?

You can initialized it to something else first, then change it to something that capture self:

init() {
  clos = {}
  clos = { [unowned self] in self.a }
}

You can have clos be implicitly unwrapped optinal if the something else is troublesome to write, but the premise is still the same.

Hi,

You can do:

class A {
    var a: Int
    lazy var clos: () -> Void = {
        return { [unowned self] in
            print(self.a)
        }
    }()
    
    init(a: Int) {
        self.a = a
    }
}

Edit: The initialization closure is actually not needed, with lazy itself is enough:

class A {
    var a: Int
    lazy var clos: () -> Void = {  [unowned self] in
        print(self.a)
    }
    
    init(a: Int) {
        self.a = a
    }
}
2 Likes
Terms of Service

Privacy Policy

Cookie Policy