Pitch: an Official Style Guide and Formatter for Swift

(Marcin Krzyzanowski) #61

most likely the proposal should include an action to remove this tool whatsoever

(Frederic Barthelemy) #62

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

gofmt for GoLang + prettier for JavaScript, TypeScript, and JSON have completely erased a huge class of discussions and distractions while making all code look consistent. Only configuration rule left is tabs vs spaces, and that gets decided at the repo level (aka once per project).

(Jeffrey Macko) #63

Thanks for bringing this up.

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

As written the proposal is great because it’s simple and doesn’t force itself upon us.

@allevato What is a coding style?

What should we enforce? Should it be pure style(like moving space, tab colon, and braces)? Or should it clean(remove unused import / remove dead code) or organize code(for example force each protocol conformance to be in an extension) and function(re-order function in file / re-order import)? Should it work on file or folder(should extension live in a separate file)?

The real debate will start when we will start to talk about the style itself and the limitation of the tool.

A few other companies started to share their style and rationale behind each aspect of it.

Since I didn’t see it mention I like the approach of this tool that gives you a way to express your own style(I know it’s not a goal for this tool now).

I think this topic will break the most talked about topic in the forum.


gofmt works great because it gives you almost no flexibility is my opinion. If swift-format will have a great flexibility, I believe that it'll defeat the purpose of providing "official style."

In other words, I'd agree on the idea of "official style" but I'm favor in the gofmt way.

(Chéyo Jiménez) #65

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.

(Shai Mishali) #66

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.

(Jeffrey Macko) #67

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

(Matt Diephouse) #68

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.

(Tony Allevato) #69

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.

(Nick Lockwood) #70

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.

(David Ungar) #71

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.

(Paul Cantrell) #72

-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.

(Boris Triebel) #73


(David) #74

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.

(DJ Mitchell) #75

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.

(Tony Allevato) #76

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.

(Tony Allevato) #77

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!

(David) #78

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?

(David) #79

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.

(Paul Cantrell) #80

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.