AR89 AR89 - 3 months ago 10
Swift Question

Swift, Observer pattern with closures

I'm trying to implement the Observer pattern in swift using only functions:

var closures: [() -> Void] = []

class A: NSObject
{
static var c = 0
var i = 0

override init()
{
super.init()
self.i = A.c
A.c += 1
}

func foo()
{
print("Hi: \(i)")
print("\(A.c)")
}
} // class

var aa:A? = A()

closures.append(aa!.foo)

for item in closures
{
item()
}

aa = A()

for item in closures
{
item()
}


this prints:

Hi: 0
1
Hi: 0
2


First question, it looks like the instance variable
i
is never modified, do you know why?

Second question, will it leak memory? Since I have an array of functions, will
aa
ever be released without emptying the array?

Third question, any better idea for an Observe pattern using just functions? (I don't want to use protocols)

Answer

I've found the solution using better keyword on google. I needed to implement the observer pattern using closures, to avoid protocolos and thus decoupling of the observer to the observables. The observer is an object with an array of closures like this one: var array:[() -> ()] = []

Each observable add it's function to this array, when it's needed the observer will call each or any function of this array. The functions are made as shown below.

lazy var someClosure: () -> String = { [unowned self, ] in // closure body goes here } To avoid retain cycles the self must be captured as unowed or weak.

Here is the article that exaplain with more details this solution: https://medium.cobeisfresh.com/why-you-shouldn-t-use-delegates-in-swift-7ef808a7f16b#.dmijmxbc4