[英]Implement protocol variable conforming to single protocol as variable conforming to several protocols
我正在嘗試做一件簡單的事情,但是代碼給出了一個錯誤: Type 'MyClass' does not meet protocol '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 一致也不起作用。 是否可以使用符合多個協議的變量作為另一個協議變量?
您會說,“使 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.