I have a class that needs to be called by a delegate when one of its properties changes. The following is a 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 } }
It all works great. 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 causes two compiler errors. First, a line declaring valueChanged in the protocol gives: Reference to generic type 'MyClass' requires arguments in <...> . Secondly, a call to valueChanged in the valueChanged observer throws: 'MyClassDelegate' does not have a member named 'valueChanged' .
I thought using 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 track, but I still have two compiler errors. The second error remains at the top, as well as a new 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 do this?
generics swift
GarlicFries Feb 19 '15 at 19:18 2015-02-19 19:18
source share