Pitch: an Official Style Guide and Formatter for Swift

Yes please. Make it an official tool with a version number that gets updated. I should be able to then apply the style version I want or I should be able to choose to always use the newest version. I can always run another tool that undoes some of the styling I can’t stand but that doesn’t matter.

I think this is a slippery slope. Even today, the "official way" Apple/Xcode formats some things is really not aesthetic. I wouldn't want to relinquish control so aggressively.

3 Likes

You are so right, after thinking more about it yes it definitely should not be very flexible.

Should there be an official style? Yes.
Should there be an official formatting tool that enforces this style? Yes.

Elm has elm-format as well, and I'm rather jealous of it. Even though it's not the style that I would necessarily choose, I appreciate the uniformity. The same would be true for Swift. (e.g. I generally prefer 4 space indents, but I anticipate that Swift would use 2 space indentation and I would adopt that.)

I'm sure there will be some ugly threads on the forums arguing over style, but I don't find that to be a compelling reason not to do something.

As a general comment on swift-format, I think that JSON is a very poor choice for a configuration format. TOML would be a much better choice, IMO, followed by YAML. I hope that we can discuss these details separately.

6 Likes

For what it's worth, I don't disagree. JSON was chosen because it's better than the other option in Foundation, which would be XML. I guess I could have used text-format protobuf, but that's more of a lateral move. If there were a TOML or YAML implementation of Encoder/Decoder available in the Swift project, I'd adopt it in a heartbeat. (I can't speak for the Swift team and IANAL but I would presume that licensing concerns might stand in the way of adopting dependencies outside the project.)

These are implementation details that can be changed in the future in a backwards-compatible way and I don't think would need evolution-style discussion (the format of the config file shouldn't be a deciding factor of the overall problem at hand), but that's just my personal opinion.

Should there be an official style? Yes.
Should there be an official formatting tool that enforces this style? Maybe not? I foresee a few problems with this.

Formatting Swift is hard (I have some experience with this), not because of the complexity of the syntax, which we already have SourceKit and LibSyntax to help with anyway, but because it's not clear where the role of the formatter should end.

We can (mostly) agree on basic stuff like whitespace between tokens, brace positions and removing semicolons. But there are plenty of things are much harder to nail down in a way that will suit the entire community. Some examples:

  • 2 or 4 space indenting
  • line width (80, 100 or 120 chars)
  • trailing commas in collection literals
  • use of explicit self for members
  • force unwrap versus guard and assert
  • for … in vs forEach

These belong in style guides, but perhaps not in the official style guide.

There are also things that should go in the official style guide and wouldn't be highly controversial, but which would be impossible to autocorrect (at least with a LibSyntax-based formatter; SourceKit based tools like SwiftLint could do it) e.g.

  • enum cases should start with lowercase names
  • types should start with uppercase
  • booleans vara should be named "isFoo" or "areFoo", etc.

Both of these categories of style rule are currently tackled by SwiftFormat and SwiftLint, but that only works because they are highly customizable, so users can disable rules if they don't like them or find that they cause API-breaking changes.

I don't think it's possible to implement an official zero-config gofmt or Prettier-style "complete" formatter for Swift that can implement everything that should be in the style guide without a significant segment of the Swift developer community refusing to use it.

If you make the rules configurable you then have a massively larger test surface and a potentially unlimited amount of extra work adding support for every possible style in use by Swift developers today.

Also - as has been pointed out - there already exist some good community tools for formatting Swift code that can easily be customized to implement whatever style rules the official guide might contain, as well as any deviations or extensions that specific teams want to add.

These tools are unlikely to ever be candidates to become "official", but relatively little is gained by starting a new formatter project that will in all likelihood never catch up to these tools, which have a 3-4 year head start.

I also fear a problem similar to that of Swift Package Manager, where Apple putting its name to an official (but low-priority, minimum-viable) tool will convince everyone that the existing, mature and feature-rich community tools are effectively dead and no longer worth supporting.

Instead of building a new formatting tool, I would prefer to see Apple adding better hooks into Xcode to support 3rd party formatting and linting tools seamlessly, and the energy of the Swift open source community directed towards improving the open source tools we already have.

19 Likes

I would rather not see an official style guide for Swift. I have not encountered a problem with reading others' Swift code, though my experience is likely different from others'. I believe that having a mandated style tends to reduce code to the lowest common denominator; rather than thinking carefully about clarity in a given case, people just run the tool, conform to the given style, and go on. For example, sometimes it's more readable to stack arguments vertically, sometimes not. But clang-format just makes the same decision, no matter what the meaning of the arguments. Another example, when three statements are all doing the same basic thing, but with different length identifiers, readability is promoted by lining things up:

foo   .wobulate()
snort .wobulate()
x     .wobulate()
// all three wobulates are suposed to line up above

Anyway, the larger point is that the better option is for folks to agree on some guidelines and then think about the layout of their code.

-1 on the heavy-handed imprimateur of a single “official style guide for the Swift language.”

I’m highly skeptical of an effort to create a single style to rule them all. @millenomi echos many of my own thoughts on this; my skepticism is even stronger. I think also of the rich and nuanced advice in @Erica_Sadun’s Swift style book, which (rightly, imo) flags so many things as a matter of judgement and personal/team taste.

I could imagine a “Swift default style,” or a style for the Swift core project itself that is the de facto default. Such a style would only need the consensus of core project contributors, which might be easier.


I’m even more skeptical of an effort to reach consensus on such a universal standard in this forum, which tends to degenerate quickly when tasked with deciding opinion-driven minutiae.

If we do go this route, I would strongly recommend some process other than open-ended discussion.

For example, we might identify a list of many possible style recommendations, conduct a one-pass thumbs up/down poll on all of them, and only include things that pass some set consensus threshold. No endless haggling.


Underlying my skepticism, I suppose, is doubt about whether there really is a problem worth solving here.

I don't find Swift code from unfamiliar projects particularly hard to read. I don't find it difficult to switch styles when necessary. If some hypothetical team out there is burning their code review time on formatting minutiae, they can and should adopt SwiftLint or similar.

The putative mental burden in the rationale isn’t so burdensome.

13 Likes

+1

2 Likes

I don't think Swift should have an official style guide. I think Swift should provide a style guide "library", and tools to integrate the style of your choice in your project. ...

Each project deserves the flexibility it needs to determine for itself what kind of style is important to it. ...

However, if we take the library and tooling approach, then teams can pick & choose, or customize, the rules that they need and move much faster towards an agreed approach that works for them.

1000 times this. Resist the mono-culture! A language is a language not a dogma. Developers are human not machines. Code is poetry, not a regurgitation of the AST. Don't take the fun out of writing software.

While go-fmt is nice for large projects where engineers are code drones, it is (somewhat ironically) one of the least inclusive features of go. Please don't hop on the Google bandwagon and force everyone to use the same style. Let users be expressive and give people the tools to enforce more rigid style where practical.

6 Likes

it is (somewhat ironically) one of the least inclusive features of go

You piqued my interest here. I did a quick Google and didn't turn up anything meaningful. Care to expand?

I'm very in favor of this proposal and would LOVE something like gofmt but a cogent case about inclusivity could sway my vote the other way.

2 Likes

First, thank you for your work in this space with SwiftFormat, Nick! I'm glad that you've added your perspective to the discussion.

For what it's worth, this isn't work that is to be started in the future—it has already been started, is linked in the pitch above, and has made a great deal of progress. You're correct that other tools already exist and have had a head start, but I disagree with the prediction that one adopted into the project "will in all likelihood never catch up to these tools". In addition to folks at Apple who would contribute, my team at Google will also continue to do so as it is one of our mandates (and we will be using it heavily internally), and we would of course be happy to accept community contributions. Indeed, I would hope that (and encourage!) authors of other tools in this space would be willing to contribute their experience to the an official one as well. We can all benefit a great deal from each others' perspectives.

You rightly pointed out that there are some kinds of checks/corrections that aren't possible with a purely syntax-based tool, and I think that's fine. I don't believe in perfection being the enemy of good, and there is room in this space for many different approaches; it's not our wish to preclude anyone from developing their own solutions that solve different—or even the same—problems in different ways. That's healthy for the community, in my opinion. But what we feel is also healthy for the community—especially newcomers to the language—is for the language tooling to provide a great out-of-the-box solution by default, and that's the problem we hope to solve here.

5 Likes

When reading comments like this, I fear that people are interpreting the pitch in subtly different ways (which I should absolutely address before moving to the proposal stage), because I'd like to stress again that we have no interest in forcing anyone to adopt a particular style. Doing so could only be achieved by refusing to compile code that didn't follow that style, which IMO is extreme and inappropriate for a language that never has and never will (I think that's safe to assume) have mandatory syntactically significant indentation.

If we end up ratifying a style and have a formatter that applies it, and someone doesn't like that style, there's nothing requiring them to run the tool or conform.

So, with that in mind:

This notion of a "default" style is effectively the upper bound of what we would be discussing. It's partly a question of what an officially adopted formatter would apply, but also what we would present to users in documentation and other media, and what we hope the Swift core projects would also adopt—but even on that last point, as we've seen in this discussion, owners of different projects under the Swift umbrella have different thoughts on style!

6 Likes

You piqued my interest here. I did a quick Google and didn't turn up anything meaningful. Care to expand?

I'm not sure I know of literature arguing that language mandated code formatters are exclusive. Perhaps I should write some...

My argument is that while go-fmt is immensely practical for many scenarios, a language-mandated one true way is naturally exclusive in all contexts where the one true way is not possible or not preferred. Others have already mentioned projects where existing styles are in place or the style, whatever it should be, may not end up matching restrictions or limitations imposed by other tools. I thought the comment about publishing Swift in literature highlights this point extremely well.

Outside of that, a mandated code format excludes code poets. Not everyone uses Swift for business. Not everyone works on a team. Not everyone reads the same.

Further, let's take a logical approach. Let's assume a mandated code format is inclusive. If this is the case there should be zero arguments as to the style in which code reads the easiest and clearest and is most accessible across the broad community. The existence of one valid (in good faith) argument as to which style this is would indicate a mandated format cannot be broadly inclusive. I'd wager I could simply remind everyone that there's one true brace style to provide one example.

I might also mention that go-fmt is the only example of a language with a mandated mono-syntax. Why was go developed? To make Google engineers more efficient at writing service business logic. I love go. But I think if Swift is really aiming to outpace go, it should avoid falling into the trap of going in a direction that primarily serves engineering teams at large companies.

ALSO, if you really really think about it, what is the actually the point? What is the point in investing tons of resources in a pretty AST printer and declaring all other syntax to be wrong. Shouldn't the incorrect syntax simply not parse in the first place?

Thank you for clarifying this. It sounds like we are in agreement, then.

I think the existence of a first class format utility is is great. I dislike the fact that pretty printing the AST has been left to 3rd parties in the past--it's klunky. I'd put a vote in for designing the format utility to ingest a declarative style sheet and provide a default sheet (or the ability to generate one) with all options specified so that the format utility can be easily tailored to specific projects and use cases.

3 Likes

Goodness, I hadn’t imagined you were proposing the compiler actually refuse to compile non-style-compliant code. That way lies madness, clearly!

Indeed? To me, “an official style guide for the Swift language” sounds significantly stronger than “a default style.”

The former carries an air of authority: “you can do it other ways if you like, but those other ways are wrong and you will pay for them.”

The latter to me means, “Here are the norms to use as a starting point. If you feel the need to develop a different style, you can describe it in terms of its deviations from the default.”

Greater clarity about these sorts of questions would certainly be helpful. Commenters in this thread certainly aren’t all imagining the same answers.


I’d also like to echo Nick’s concerns about redundancy with existing projects.

As much as I like the promise of SPM, he’s quite right about the damage it did by being both the most official and the least functional package manager.

“We can all learn from each others’ perspective” would be a perfectly valid answer if this proposal were for an independent open source project existing in a “many flowers bloom” context, but it’s not. If this is the official formatter, it will suck the air out of whatever projects it displaces — even if they are more mature, more battle-tested, better suited to actual usage.


Sorry to dump so many concerns on this proposal. A clearer description of how you imagining it playing out in practice might help it sit better.

7 Likes

I am strongly in the camp that says we should improve the official tooling in this area, but that we should not have an “official style”. I really like this suggestion by @Tony_Parker that this tooling should be oriented towards supporting style decisions made by each team using Swift.

I think it would be fine to have a default configuration of this tooling aligned with a default style. But I agree with @Paul_Cantrell that there is a very important distinction between a default style and an “official” or “recommended” style. I’m sure that even if my preferred style were adopted as the “official” style, before long I would regret having rigidly committed to adopting that style forever.

I would like to hear more specific concerns about the impact on automated code transformations mentioned which was mentioned by @Joe_Groff. That said, my instinct is that I wouldn’t necessarily expect these tools to apply the precise style I intend and would be willing to re-apply my style afterwards if necessary. I can’t imagine it would be worse than some of the behavior Xcode exhibits today.

8 Likes

+1 Official Style Guide
+1 Official Style Formatter
+1 Option to define custom styling rules to be enforced by the formatter

Can you elaborate on why that is? I'm interested in hearing these points of view because my position is traditionally the opposite: "I don't care what the style guidelines are as long as they're within reason, the important thing is I don't have to think about them anymore either when writing or reviewing code." I'm more interested in having a common or official style for the educational and logistical aspects, not necessarily for advocating for a particular style at the expense of others.

There are certain knobs that I think need to exist for practical reasons (for example, being able to adjust column limit is important when code is written or viewed in multiple tools that may not all handle wrapping the same way), but for other things like whether line breaks are preferred before or after operators, I code in various languages with slightly different guidelines and I don't end up opinionated about them because I just let the formatter take care of it for me. It only becomes something I care about if I'm involved in actually deciding the rules, in which case I'll naturally make the case for my preference, but I won't oppose or regret reasonable alternatives if the consensus ends up being something different.

9 Likes

A single, official style would be really great - until you discover the first choice in it that you consider to be utterly terrible.
It's not realistic that everyone or even just a majority agrees on a single set of rules, so whatever you choose, many people will be disappointed.
I think this will be true no matter how strict the enforcement is: As soon as there is an official style, anyone who disagrees with it will be constantly exposed to backlash, and I'd rather prefer that backlash coming from a tool like gofmt than from other developers; I don't think that having a "recommended" style is a good idea at all.

I'm not sure how many options are truly polarizing, but if it's just tabs vs spaces, having this as a single degree of freedom might give us most benefits of uniformity without repelling a large group of users.

3 Likes