Question Details

No question body available.

Tags

swift generics associated-types

Answers (2)

January 21, 2026 Score: 1 Rep: 30,363 Quality: Medium Completeness: 60%

Your exact formulation isn't allowed in Swift because the full type of an associatedtype must be known at adoption time (and Collection for an unspecified X isn't valid). If you don't care what X actually is at any point, then @JoakimDanielson's answer is the simplest and easiest - but if you do need to constrain X in some way, then you can incorporate it into the protocol by making SomeProtocol itself generic on X:

protocol SomeProtocol { // X is the primary associatedtype associatedtype X associatedtype T: Collection where T.Element == X }

Then, to adopt:

struct SomeStruct: SomeProtocol { typealias T = Array }

struct OtherStruct { let value: T.T }

In use:

let s: OtherStruct = .init(value: ["a", "b", "c"]) print(s) // => OtherStruct(value: ["a", "b", "c"])
January 21, 2026 Score: 1 Rep: 53,142 Quality: Low Completeness: 50%

I think you can skip X in your protocol definition since it's already known that Collection is a generic type

protocol SomeProtocol { associatedtype T: Collection }

And then your types can be declared as

struct SomeStruct: SomeProtocol { typealias T = Array }

struct OtherStruct { let value: T.T }

Example

let y: OtherStruct = .init(value: [1, 2, 3])