Say I have a very simple class:
class Box<T> {
var boxedObject:T
init(object: T) {
self.boxedObject = object
}
}
Now I would like to add a delegate who can tell me that the value in the field has changed:
protocol BoxDelegate<T>: class {
func valueInBoxChanged(box: Box<T>) -> Void
}
class Box<T> {
var boxedObject: T {
didSet {
self.delegate?.valueInBoxChanged(self)
}
}
weak var delegate: BoxDelegate<T>?
init(object: T) {
self.boxedObject = object
}
}
This code, of course, does not work, because we do not have common delegates. I can make the delegate a closure structure, but this is a bit ugly solution. How should I do such things in Swift?
source
share