Create a shared delegate for the class

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?

+4
source share
1 answer

Due to the limited protocol type with Swift, you may not be able to do what you tried to do above. What you could do is create a closure when the delegate is installed and close the closure later.

Here is what would make your case simpler,

protocol BoxDelegate: class {
    associatedtype T
    func valueInBoxChanged(box: Box<T>) -> Void
}

class Box<T> {

    var notifyClosure: (Void -> Void)?

    var boxedObject: T {
        didSet {
            self.notifyClosure?()
        }
    }

    func setBoxDelegate<M where M:BoxDelegate, M.T == T>(delegate: M) {
        notifyClosure = {
            delegate.valueInBoxChanged(self)
        }
    }

    init(object: T) {
        self.boxedObject = object
    }
}

, , . BoxDelegate, .

0

All Articles