AR89 AR89 - 1 month ago 3x
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()
self.i = A.c
A.c += 1

func foo()
print("Hi: \(i)")
} // class

var aa:A? = A()


for item in closures

aa = A()

for item in closures

this prints:

Hi: 0
Hi: 0

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

Second question, will it leak memory? Since I have an array of functions, will
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)


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: