将函数泛型参数约束到关联类型

时间:2016-03-28 12:59:44

标签: swift generics xcode7.3

为什么这会在函数声明行上显示以下内容: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) { }
}

1 个答案:

答案 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) { }
}
相关问题