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)
Aucun commentaire:
Enregistrer un commentaire