您可以让“通用”委托类型成为异构协议,您可以分别遵循您希望泛型 A 和 B 的类型,从而允许将 Type1 和 Type2 用作实际在委托协议的“通用”方法蓝图中键入。
设置泛型类型约束Type1 和Type2(限制:它们必须是异构的)和委托协议MyClassDelegate:
/* Generic type constraints */
protocol Type1: CustomStringConvertible {
init(_ value: Int)
func foo()
}
protocol Type2: CustomStringConvertible {
init(_ value: Int)
func bar()
}
/* Delegate protocol */
protocol MyClassDelegate {
func decorate(first: Type1, second: Type2) -> Void
}
使用“通用”委托设置两个示例类,用于从一个类到另一个类的回调。
/* class using the delegate */
class MyDifferentClass<A: Type1, B: Type2> {
var foo: A = A(0)
var bar: B = B(0)
var delegate: MyClassDelegate?
var someInt : Int = 1 {
didSet {
delegate?.decorate(foo, second: bar)
}
}
}
/* class conforming to MyClassDelegate */
class MyCurrentClass<A: Type1, B: Type2>: MyClassDelegate {
var myDifferentClass = MyDifferentClass<A, B>()
init() {
myDifferentClass.delegate = self
}
// MyClassDelegate
func decorate(first: Type1, second: Type2) {
first.foo()
second.bar()
print("first: \(first)", "second: \(second)")
// ...
}
}
示例类型:
/* conforming some types to your generic type (constraint) protocols */
extension Int: Type1 {
func foo() {
print("foo!")
}
}
extension Double: Type2 {
func bar() {
print("bar!")
}
}
示例用法:
/* Example usage */
var a = MyCurrentClass<Int, Double>()
a.myDifferentClass.someInt += 1
/* foo!
bar!
first: 0 second: 0.0 */
只要类型约束协议Type1 和Type2 是异构的,即不包含某些关联类型本身,此方法就有效。