I have a class that needs to call out to a delegate when one of its properties changes. Here are the simplified class and protocol for the delegate:
protocol MyClassDelegate: class { func valueChanged(myClass: MyClass) } class MyClass { weak var delegate: MyClassDelegate? var currentValue: Int { didSet { if let actualDelegate = delegate { actualDelegate.valueChanged(self) } } } init(initialValue: Int) { currentValue = initialValue } } This all works just fine. But, I want to make this class generic. So, I tried this:
protocol MyClassDelegate: class { func valueChanged(genericClass: MyClass) } class MyClass<T> { weak var delegate: MyClassDelegate? var currentValue: T { didSet { if let actualDelegate = delegate { actualDelegate.valueChanged(self) } } } init(initialValue: T) { currentValue = initialValue } } This throws two compiler errors. First, the line declaring valueChanged in the protocol gives: Reference to generic type 'MyClass' requires arguments in <...>. Second, the call to valueChanged in the didSet watcher throws: 'MyClassDelegate' does not have a member named 'valueChanged'.
I thought using a typealias would solve the problem:
protocol MyClassDelegate: class { typealias MyClassValueType func valueChanged(genericClass: MyClass<MyClassValueType>) } class MyClass<T> { weak var delegate: MyClassDelegate? var currentValue: T { didSet { if let actualDelegate = delegate { actualDelegate.valueChanged(self) } } } init(initialValue: T) { currentValue = initialValue } } I seem to be on the right path, but I still have two compiler errors. The second error from above remains, as well as a new one on the line declaring the delegate property of MyClass: Protocol 'MyClassDelegate' can only be used as a generic constraint because it has Self or associated type requirements.
Is there any way to accomplish this?