Swift中的多级泛型类型约束

时间:2018-04-12 00:20:31

标签: swift generics

我不确定问题的标题是否正确,但假设我们在下面定义了2个通用结构FooBar

// Foo
struct Foo<T> {
}

// Bar
struct Bar<U: Codable> {
}

我想在Foo上创建一个扩展程序,其中T被限制为等于Bar,同时保持Bar.U符合Codable的约束

基本上,我该如何做以下的事情?

extension Foo where T == Bar<U: Codable> {
}

上面没有编译。使用符合Codableextension Foo where T == Bar<String>)的具体类型可以起作用,但这会将扩展名限制为只有一种具体类型的Codable

我将不胜感激任何帮助/见解。谢谢。

1 个答案:

答案 0 :(得分:3)

我不确定您是否正在寻找,但您可以使用相关类型的协议来执行此操作:

struct Foo<T> { }

protocol BarProtocol {
     associatedtype U: Codable
}

struct Bar<U: Codable>: BarProtocol {

}

// Now this works
extension Foo where T: BarProtocol {
    // T.U can be of any type that implements Codable
}

编辑 - 改为T:BarProtocol,谢谢Marcel!

相关问题