Multiline class declarations

Hello everyone. Swift follows the POP way, which means we use generics actively. This leads, however, that my class declarations look really long especially if a used generic has an associated type. Just for example:

final class DoingSomethingObject<NestedThing: SomeProtocol>: AnotherProtocol, OneMoreProtocol where NestedThing.First == Int, NestedThing.Second == String {
}

Apple's guidelines about human readable names, descriptive generics' names, such a strange syntax of restricting types of protocols' associated types, all of that often take more than one line and I cannot even put "where ........" on the next line with a 4 digit indent because Xcode thinks there should not be any indents. Does anyone face the same problem? How do you solve this?

The official formatter currently does this with your example:

final class DoingSomethingObject<NestedThing: SomeProtocol>: AnotherProtocol, OneMoreProtocol
where NestedThing.First == Int, NestedThing.Second == String {
}

I also habitually move conformances out of the generic arguments into the where clause:

final class DoingSomethingObject<NestedThing>: AnotherProtocol, OneMoreProtocol
where NestedThing: SomeProtocol, NestedThing.First == Int, NestedThing.Second == String {
}

Manually breaking it up into more lines (as though it were much longer) before running it through the formatter yields this:

final class DoingSomethingObject<NestedThing>:
  AnotherProtocol,
  OneMoreProtocol
where
  NestedThing: SomeProtocol,
  NestedThing.First == Int,
  NestedThing.Second == String
{
}

I guess if you don’t like any of those, you could bring up whatever improvement suggestions you have in the “Development: Swift Format” category.

1 Like

Xcode will indent the where clause if you put the opening brace on the next line:

final class DoingSomethingObject<NestedThing: SomeProtocol>: AnotherProtocol, OneMoreProtocol
  where NestedThing.First == Int, NestedThing.Second == String
{
  // ...
}
1 Like

This looks much more readable than my way, thank you guys for these variants :blush:

Terms of Service

Privacy Policy

Cookie Policy