0

Example:

class A {
   var fn: (() -> ())? = nil
}

class B {
   let a = A()
   init() {
      a.fn = someFn
   }

   func someFn() {
   }
}

Now we have cyclic reference, because B owns A by direct ref a and A implicitly owns B by self owned in fn closure (correct me if I'm wrong).

Possible solutions is:

  1. weak var fn is not good for my case because I'm assigning not only methods. 'weak' may only be applied to class and class-bound protocol types.
  2. a.fn = { [unowned self] in self.someFn() } is correct solution, but too verbose.

Is there any other solutions?

vlastachu
  • 257
  • 3
  • 18
  • 1
    Well `weak var fn` won't compile as you cannot apply the `weak` attribute to function types ;) – Hamish Jan 04 '17 at 16:38
  • 2
    Related: [How to remove strong reference cycle from closure from method?](http://stackoverflow.com/questions/39899051/how-to-remove-strong-reference-cycle-from-closure-from-method) – Hamish Jan 04 '17 at 16:39
  • @Hamish yes. The questions is same, thx. And yes my first solution is wrong and second is the single possible solution. – vlastachu Jan 04 '17 at 16:49
  • [This question/answers](http://stackoverflow.com/questions/24320347/shall-we-always-use-unowned-self-inside-closure-in-swift) might be useful... – Ahmad F Jan 04 '17 at 16:58

0 Answers0