这很有趣。它appears一旦你限制了一个类型associatedtype
在给定的协议中,您需要在该协议的实现中提供具体类型(而不是其他协议类型)——这就是第二个示例起作用的原因。
如果您删除A
对关联类型的约束,您的第一个示例将起作用(减去有关无法使用的错误weak
在非类类型上,但这似乎不相关)。
话虽这么说,我似乎找不到任何文档来证实这一点。如果有人能找到一些东西来支持这一点(或完全质疑它),我很想知道!
为了让当前的代码正常工作,您可以使用泛型。这实际上会一石二鸟,因为您的代码现在都将编译,并且您将受益于泛型带来的增强的类型安全性(通过推断您传递给它们的类型)。
例如:
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?
}
Edit:看来上述解决方案在您的特定情况下不起作用,因为您想避免使用具体类型。我会把它留在这里,以防对其他人有用。
根据您的具体情况,您may能够使用类型擦除来为您创建伪具体类型B
协议。Rob Napier 有一篇很棒的文章关于类型擦除。
在这种情况下,这是一个有点奇怪的解决方案(因为类型擦除通常用于包装协议associatedtypes
),而且它也绝对不如上面的解决方案,因为你必须为你的每个方法重新实现一个“代理”方法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
协议类型,而不对其进行更多类型限制。