将符合单个协议的协议变量实现为符合多个协议的变量

时间:2020-08-24 11:25:26

标签: ios swift

我正在尝试做一个简单的事情,但是代码给出了一个错误:类型'MyClass'不符合协议'MyProtocol3'

protocol MyProtocol1 {

}

protocol MyProtocol2 {

}

protocol MyProtocol3 {
    var output: MyProtocol2 { get }
}

class MyClass: MyProtocol3 {

    var output: MyProtocol2 & MyProtocol1

    init(output: MyProtocol1 & MyProtocol2) {
        self.output = output
    }
}

使MyProtocol2符合MyProtocol1也不能解决问题。是否可以将符合多种协议的变量用作另一个协议var?

1 个答案:

答案 0 :(得分:0)

您说,“使MyProtocol2符合MyProtocol1也不起作用。”除非您有未提及的窍门,否则在我看来,它就是答案。

以下在操场上的作品:

protocol MyProtocol1 {
    func test1()
}

protocol MyProtocol2: MyProtocol1 {
    func test2()
}

class OutputClass: MyProtocol2 {
    func test1() {
        print("test1")
    }
    func test2() {
        print("test2")
    }
}

protocol MyProtocol3 {
    var output: MyProtocol2 { get }
}

class MyClass: MyProtocol3 {

    var output: MyProtocol2

    init(output: MyProtocol2) {
        self.output = output
    }
}

let o = OutputClass()
o.test1()
o.test2()
let m = MyClass(output: o)