[英]Constrain function generic parameter to associated type
为什么这样会失败并显示以下内容: Inheritance from non-protocol, non-class type
函数声明行上的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
}
...类型FA
是完全不受约束的,因此它很可能是一个Int
,您不能使用:
语法继承或遵循它。
如果您确实需要比(a: FA)
更通用的解决方案,那么可以遵循以下方法:
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) { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.