Protocol associatedtype作为委托的类型

时间:2018-02-28 12:22:32

标签: swift generics inheritance delegates protocols

我想要做的目的是为了能够将实现 conn.ConnectionString = "Server=localhost;Database=MIN-MAK MRO;Trusted_Connection=true"; conn.Open(); SqlCommand command = new SqlCommand("SELECT Top 1 FirstName FROM HistoryReport ", conn); 的对象放到一个数组中(查看AbstractClass - > children)并放入每个 ChildOfRootClass 实例对象指向其父级的链接(查看 ChildNClass 变量)。所以我想在每个 weak var delegate 泛型中使用 delegate 的类型。

希望代码将解释我的意思。

ChildOfRootClass

为每个孩子委派协议。

    // Parent class for RootClass and Child1Class, Child2Class etc
    class AbstractClass {
        init() { }
        init(smth: String) { }

        var children = [String : ChildOfRootClass]()

        func add(key: String, child: ChildOfRootClass) {
            children[key] = child
        }
    }

儿童班。

    protocol ChildDelegate: class { }
    protocol Child1ClassDelegate: ChildDelegate { func rr() }
    protocol Child2ClassDelegate: ChildDelegate { }

    class RootClass: AbstractClass {
        override init() {
            super.init()
        }
    }

    extension RootClass: Child1ClassDelegate {
        func rr() { }
    }

我想如何使用它。

    protocol ChildOfRootClass {
        associatedtype ChildOfRootClassDelegateType: ChildDelegate

        weak var delegate: ChildOfRootClassDelegateType? { set get }
        init(smth: String)
    }

    class Child1Class: AbstractClass, ChildOfRootClass {
        typealias ChildOfRootClassDelegateType = Child1Delegate

        weak var delegate: Child1Delegate?

        required override init(smth: String) {
            super.init(smth: smth)
        }
    }

    extension Child1Class: Child2ClassDelegate { }

    class Child2Class: AbstractClass/*, ChildOfRootClass*/ {
        required override init(smth: String) {
            super.init(smth: smth)
        }
    }

0 个答案:

没有答案