繁体   English   中英

将函数通用参数约束为关联的类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM