为什么这会失败并显示以下内容: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) { }
}
请注意,以下编译:
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
是完全不受约束的,所以它很可能是,比如说, an Int
,你不能从它继承或遵守使用:
语法。
如果您真的需要一个比(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) { }
}