在我的 swift项目中,我有一个案例,我使用协议继承如下 protocol A : class{}protocol B : A{} 我接下来想要实现的是声明另一个具有关联类型的协议,一种必须从协议A继承的类型.如果我尝试将其声
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.如果我理解正确,那就意味着B
我试图声明并询问如何声明从协议A继承的关联类型时不采用A?
我基于以下事实编译得很好的事实做出了上述假设
class SomeDummyClass : B{
}
class SomeClass : AnotherProtocol{
typealias Type = SomeDummyClass
weak var type : Type?
}
这非常有趣.看来,一旦你约束给定协议中关联类型的类型,你需要在该协议的实现中提供一个具体类型(而不是另一种协议类型) – 这就是你的第二个例子工作的原因.
如果删除关联类型的A约束,则第一个示例将起作用(减去关于无法在非类类型上使用弱的错误,但这似乎并不相关).
尽管如此,我似乎无法找到任何文件来证实这一点.如果有人能找到一些东西来支持(或完全争议),我很想知道!
要使当前代码正常工作,您可以使用泛型.这实际上会一举两得,因为你的代码现在都会编译,你将从泛型带来的类型安全性增加中受益(通过推断传递给它们的类型).
例如:
protocol A : class {}
protocol B : A {}
protocol AnotherProtocol{
associatedtype Type : A
weak var type : Type? {get set}
}
class SomeClass<T:B> : AnotherProtocol {
typealias Type = T
weak var type : Type?
}
编辑:看起来上述解决方案在您的特定情况下不起作用,因为您要避免使用具体类型.我会留在这里,以防它对其他人有用.
在您的特定情况下,您可以使用类型擦除来为B协议创建伪混凝土类型. Rob Napier has a great article关于类型擦除.
在这种情况下,这是一个奇怪的解决方案(因为类型擦除通常用于包装具有关联类型的协议),并且它也肯定不如上述解决方案更优选,因为您必须为每个方法重新实现“代理”方法在你的A& B协议 – 但它应该适合你.
例如:
protocol A:class {
func doSomethingInA() -> String
}
protocol B : A {
func doSomethingInB(foo:Int)
func doSomethingElseInB(foo:Int)->Int
}
// a pseudo concrete type to wrap a class that conforms to B,
// by storing the methods that it implements.
class AnyB:B {
// proxy method storage
private let _doSomethingInA:(Void)->String
private let _doSomethingInB:(Int)->Void
private let _doSomethingElseInB:(Int)->Int
// initialise proxy methods
init<Base:B>(_ base:Base) {
_doSomethingInA = base.doSomethingInA
_doSomethingInB = base.doSomethingInB
_doSomethingElseInB = base.doSomethingElseInB
}
// implement the proxy methods
func doSomethingInA() -> String {return _doSomethingInA()}
func doSomethingInB(foo: Int) {_doSomethingInB(foo)}
func doSomethingElseInB(foo: Int) -> Int {return _doSomethingElseInB(foo)}
}
protocol AnotherProtocol{
associatedtype Type:A
weak var type : Type? {get set}
}
class SomeClass : AnotherProtocol {
typealias Type = AnyB
weak var type : Type?
}
class AType:B {
// implement the methods here..
}
class AnotherType:B {
// implement the methods here..
}
// your SomeClass instance
let c = SomeClass()
// set it to an AType instance
c.type = AnyB(AType())
// set it to an AnotherType instance
c.type = AnyB(AnotherType())
// call your methods like normal
c.type?.doSomethingInA()
c.type?.doSomethingInB(5)
c.type?.doSomethingElseInB(4)
您现在可以使用AnyB类型代替使用B协议类型,而不再使其具有类型限制.
