Skip to content

Instantly share code, notes, and snippets.

@zakkhoyt
Created July 15, 2017 04:02
Show Gist options
  • Save zakkhoyt/0b2543bb5a5995b41e73bef83391c378 to your computer and use it in GitHub Desktop.
Save zakkhoyt/0b2543bb5a5995b41e73bef83391c378 to your computer and use it in GitHub Desktop.
How can I distunguish which's object's generic delegate is calling the generic delegate function? thing1 or thing2?
// MyClass is generic, and has a generic delegate.
// AClass creates two instances of MyClass and implements MyClassDelegate
//
// In the implementation of MyClassDelegate, how can I distinguish which object's delegate is calling
// func myClass<T>(_ myClass: MyClass<T>, valueDidChange value: T)
//
// See comments at end of file
protocol MyClassDelegate: class {
func myClass<T>(_ myClass: MyClass<T>, valueDidChange value: T)
}
class MyClass<T: Comparable> {
private var _value: T
var value: T {
set {
delegate?.myClass(self, valueDidChange: newValue)
}
get {
return _value
}
}
var delegate: MyClassDelegate?
init(value: T) {
_value = value
}
}
class AClass {
private var thing1 = MyClass(value: Int(0))
private var thing2 = MyClass(value: TimeInterval(0))
init() {
thing1.delegate = self
thing2.delegate = self
}
}
extension AClass: MyClassDelegate {
func myClass<T>(_ myClass: MyClass<T>, valueDidChange value: T) {
// This fails to complile
// Binary operator '==' cannot be applied to operands of type 'MyClass<T>' and 'MyClass<Int>'
if myClass == thing1 {
}
// Binary operator '==' cannot be applied to operands of type 'MyClass<T>' and 'MyClass<TimeInterval>' (aka 'MyClass<Double>')
else if myClass == thing2 {
}
}
}
@ajeetpratap
Copy link

Were you able to solve this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment