Define shorthand generic function with Protocols with same primary associated types

Given protocols with the same underlying associated type, is there a shorthand syntax to apply the primary type to all of them together in a function parameter?

For example:

protocol Protocol1<Primitive> {
    associatedtype Primitive
    var p1: Primitive { get }
}

protocol Protocol2<Primitive> {
    associatedtype Primitive
    var p2: Primitive { get }
}

protocol Protocol3<Primitive> {
    associatedtype Primitive
    var p3: Primitive { get }
}

func printSum(_ thing: some Protocol1<Double> & Protocol2<Double> & Protocol3<Double>) {
    print(thing.p1 + thing.p2 + thing.p3)
}

// can we simplify this to:

func printSum(_ thing: some (Protocol1 & Protocol2 & Protocol3)<Double>) {
    print(thing.p1 + thing.p2 + thing.p3)
}

I thiiink you can do it with a separate typealias, but I haven’t tested:

typealias Protocol123<Primitive> = Protocol1<Primitive> & Protocol2<Primitive> & Protocol3<Primitive>
func printSum(_ thing: some Protocol123<Double>) {}

Yeah, you can do it with a typealias. Hopefully that means it's a simple compiler enhancement to be able to do it inline.

In your case they all have the same name so it suffices to constrain one:

func printSum(_ thing: some Protocol1 & Protocol2 & Protocol3<Double>) {
1 Like