Faiçal
Faiçal

Reputation: 72

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.

// 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.

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.

I will appreciate any help/insights. Thank you.

Upvotes: 1

Views: 540

Answers (1)

Julien Perrenoud
Julien Perrenoud

Reputation: 1591

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!

Upvotes: 3

Related Questions