为什么这会在函数声明行上显示以下内容:Inheritance from non-protocol, non-class type
?
protocol Foo {
associatedtype AType
}
struct Container<F: Foo> {
let foo: F
func doWork<S: F.AType>(s: S) { }
}
答案 0 :(得分:1)
请注意以下编译:
protocol Foo {
associatedtype A
}
struct Container<F: Foo> {
func f(a: F.A) { }
}
然而,在以下情况下:
struct Container<F: Foo> {
func f<A : F.A>(a: A) { } // error: inheritance from non-protocol, non-class type
}
...类型F.A
完全不受约束,因此它可能是Int
,您无法继承或遵守:
语法。< / p>
如果你真的需要一个比(a: F.A)
更通用的解决方案,那么沿着这些方向可以做到这一点:
protocol Bar { }
protocol Foo {
associatedtype A : Bar
}
struct Container<F: Foo> {
func f<A : Bar>(a: A) { }
}
现在,您可以使用a
协议表达对Bar
参数的任何期望。
更好的是,您可以将该方法实现为Foo
的扩展名:
protocol Foo {
associatedtype A
func f(_: A) // if you want this to be a requirement
}
extension Foo /* where A is constrained so you can do something with it */ {
func f(a: A) { }
}