Preferred declaration style for generic types with constraints

Is there a preferred style for declarations with type constraints, specifically when choosing between the following styles for MyClass1 and MyClass2 as in the following example? If yes, is there a technical reason for it?

It got me thinking because I prefer the latter and incidentally noticed that Xcode does not handle it well (note the missing MyClass2 in the document structure dropdown, for which I filed FB24626654):

class BaseClass {}

protocol BaseProtocol {}

protocol P1<T1, T2> {
  associatedtype T1
  associatedtype T2
}

protocol P2<T3, T4> {
  associatedtype T3
  associatedtype T4
}

class MyClass1<A: P1, B: P2<A.T1, A.T2>>: BaseClass, BaseProtocol {
  func f1() {}
}

class MyClass2<A, B>: BaseClass, BaseProtocol
where  A: P1,  B: P2,  A.T1 == B.T3,  A.T2 == B.T4 {
  func f2() {}
}
1 Like

In my opinion the first way is easier to read so I prefer this way, but don’t know if this is the common option.

1 Like

First one until the line's too long, then switch entirely to the second.

3 Likes

I don't think the Swift book prefers one way or the other as it documents both (type constraint syntax and generic where clauses). It may encourage the second way more when working with associated types.

I usually write my generic types the first way when I'm working with only a couple generics and constraints, otherwise writing it the second way is easier in the long run and is more widely used (in terms of extensions, protocols and assciated types). Inserting a newline after each constraint is usually my goto either way but that's personal preference.