Swift中的通用委托实现

时间:2016-02-10 12:06:55

标签: ios swift generics

鉴于课程

Calss<A: Type1, B: Type2>

是否可以在类中创建一个委托(协议)属性,该属性将使用类中的泛型类型?例如

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

换句话说,在创建泛型类委托协议时如何实现类型安全?

1 个答案:

答案 0 :(得分:0)

您可以让“通用”委托类型成为异构协议,您可以将符合要求类型AB的类型分别设置为允许Type1和{{ 1}}在委托协议的“通用”方法蓝图中用作实际类型。

设置泛型类型约束Type2Type1(限制:这些必须是异构的)和委托协议Type2

MyClassDelegate

使用“generic”委托设置两个示例类,用于从一个类到另一个类的回调。

/* 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是异构的,即本身不包含某些关联类型,此方法就有效。