简体   繁体   English

Swift中的多级泛型类型约束

[英]Multi-level generic type constraints in Swift

I'm not sure if the title of the question is right but assuming we have 2 generic structs Foo and Bar defined below. 我不确定问题的标题是否正确,但假设我们在下面定义了2个通用结构FooBar

// Foo
struct Foo<T> {
}

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

I would like to create an extension on Foo where T is constrained to be equal to Bar while maintaining the constraint that Bar.U conforms to Codable . 我想在Foo上创建一个扩展,其中T被约束为等于Bar同时保持Bar.U符合Codable的约束。

Basically, how can I do something like the following? 基本上,我该如何做以下的事情?

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

The above doesn't compile. 以上不编译。 Using a concrete type that conforms to Codable ( extension Foo where T == Bar<String> ) works but then, that limits the extension to only one concrete type of Codable . 使用符合Codableextension Foo where T == Bar<String> )的具体类型可以工作但是,这将扩展限制为只有一种具体类型的Codable

I will appreciate any help/insights. 我将不胜感激任何帮助/见解。 Thank you. 谢谢。

I'm not sure if that's what you're looking for, but you can do it using a protocol with associated type: 我不确定这是否是您正在寻找的,但您可以使用相关类型的协议来实现:

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
}

Edit - Changed to T: BarProtocol, thanks Marcel! 编辑 - 改为T:BarProtocol,谢谢Marcel!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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