Swift Closure retain cycles

501 Views Asked by At

I'd like to know if the following counts as a retained cycle:

class MyViewController: UIViewController {
  var foo: Int = 3

  func fooBar() {
    let closure = {(x: Int) in 
      print(x > self.foo)
    }
    closure(100) // Does this cause a retain cycle???

    g.doMore(100) // Now, does THIS cause a retain cycle??
  }


}

If so, how can I fix it?... Investigating some memory leak issue here. I found this syntax which apparently will release self but I don't totally comprehend how..

func fooBar() {
  let closure = {[weak self] (x: Int) in 
    print(x > self.foo)
  }
  closure(100) // Does this cause a retain cycle???
}

EDIT: To make this more exciting, let's say I have a global variable

class MyGlobalVariableClass {
  var y: Int = 3

  func doMore(a: Int) {
    let closure = {(n: Int) in
      print(n > self.y) 
    }
    closure(a)
  }
}

Say I keep a global instance of this somewhere in my code: let g = MyGlobalVariableClass()

Would using g.doMore() in my previous view controller cause a cycle?

0

There are 0 best solutions below