【问题标题】:Generic delegate implementation in SwiftSwift 中的通用委托实现
【发布时间】:2016-02-10 12:06:54
【问题描述】:

给定班级

Calss<A: Type1, B: Type2>

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

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

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

【问题讨论】:

  • 是的。这就是我最初的想法。
  • 更新了一种可能的解决方法;但是仅限于类型约束(Type1Type2),它们本身可用作类型(异构协议)。

标签: ios swift generics


【解决方案1】:

您可以让“通用”委托类型成为异构协议,您可以分别遵循您希望泛型 AB 的类型,从而允许将 Type1Type2 用作实际在委托协议的“通用”方法蓝图中键入。


设置泛型类型约束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
}

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

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

只要类型约束协议Type1Type2 是异构的,即不包含某些关联类型本身,此方法就有效。

【讨论】:

  • 不完全是我的想法,但在某些情况下适用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多