简体   繁体   English

Swift中的通用委托实现

[英]Generic delegate implementation in Swift

Given the class 鉴于上课

Calss<A: Type1, B: Type2>

would it be possible to create a delegate(protocol) property inside the class which would use a generic type from the class? 是否可以在类中创建一个委托(协议)属性,该属性将使用类中的泛型类型? eg 例如

protocol CalssDelegate{
    func decorate(first: A, second: B) -> Void
}

In other words, how would I achieve type safety when creating a generic class delegate protocol? 换句话说,在创建泛型类委托协议时如何实现类型安全?

You could let the "generic" delegate types be heterogenous protocols, to which you conform the types that you want generics A and B , respectively, which allows Type1 and Type2 to be used as actual types in the "generic" method blueprints of your delegate protocol. 您可以让“通用”委托类型成为异构协议,您可以将符合类别的类型分别与泛型AB ,这样可以将Type1Type2用作Type2的“通用”方法蓝图中的实际类型协议。


Setting up the generic type constraints Type1 and Type2 (limitation: these must be heterogeneous) and the delegate protocol MyClassDelegate : 设置泛型类型约束Type1Type2 (限制:这些必须是异构的)和委托协议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
}

Setting up two example classes using the "generic" delegate for callbacks from one class to the other. 使用“generic”委托设置两个示例类,用于从一个类到另一个类的回调。

/* 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)")

        // ...
    }
}

Example types: 示例类型:

/* 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: 用法示例:

/* Example usage */
var a = MyCurrentClass<Int, Double>()

a.myDifferentClass.someInt += 1
/* foo!
   bar!
   first: 0 second: 0.0 */

This method is valid as long as type constraint protocols Type1 and Type2 are heterogeneous, ie, don't contain some associated types themselves. 只要类型约束协议Type1Type2是异构的,即本身不包含某些关联类型,此方法就有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM