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 MyC
Protocols can have type requirements but cannot be generic; and protocols with type requirements can be used as generic constraints, but they cannot be used to type values. Because of this, you won't be able to reference your protocol type from your generic class if you go this path.
If your delegation protocol is very simple (like one or two methods), you can accept closures instead of a protocol object:
class MyClass {
var valueChanged: (MyClass) -> Void
}
class Delegate {
func valueChanged(obj: MyClass) {
print("object changed")
}
}
let d = Delegate()
let x = MyClass()
x.valueChanged = d.valueChanged
You can extend the concept to a struct holding a bunch of closures:
class MyClass {
var delegate: PseudoProtocol
}
struct PseudoProtocol {
var valueWillChange: (MyClass) -> Bool
var valueDidChange: (MyClass) -> Void
}
Be extra careful with memory management, though, because blocks have a strong reference to the object that they refer to. In contrast, delegates are typically weak references to avoid cycles.