在我的Swift项目中,我有一个使用协议继承的情况,如下所示:
编译失败,错误表示
我基于以下事实做出上述假设,因为以下情况可以成功编译。
protocol A : class{
}
protocol B : A{
}
我接下来想要实现的是声明另一个带有关联类型的协议,这个关联类型必须继承自协议A
。如果我试图这样声明:
protocol AnotherProtocol{
associatedtype Type : A
weak var type : Type?{get set}
}
代码编译没有错误,但在尝试使用AnotherProtocol
时,出现了以下情况:
class SomeClass : AnotherProtocol{
typealias Type = B
weak var type : Type?
}
编译失败,错误表示
SomeClass
不符合AnotherProtocol
。如果我理解正确,这意味着在我尝试声明并询问如何声明从协议A
继承的关联类型时,B
没有采用A
。我基于以下事实做出上述假设,因为以下情况可以成功编译。
class SomeDummyClass : B{
}
class SomeClass : AnotherProtocol{
typealias Type = SomeDummyClass
weak var type : Type?
}
weak
,只需在创建SomeClass
实例时提供type
属性的实际具体类型即可,例如:let c = SomeClass<符合B协议的您的类型>()
,或者这不是您能够做到的吗? - HamishAnotherProtocol
的类不应该能够访问在协议中未指定的类型,并且声明let c = SomeClass<B>()
也不起作用。 - Zell B.