Pitch: an Official Style Guide and Formatter for Swift


#162

I was always confused as to why Apple didn't provide a styling guide! Of course, it can't be definitive but it would go a long way, especially for beginners.

Should there be an official style? Yes.
Should there be an official formatting tool that enforces this style? Yes.
Should that official formatting tool be configurable? Yes x 1 million (if this is no, forget about the above)

First and foremost, code styling is highly debatable and even if Apple or The Swift Team provided one, we would definitely still be arguing about it.

However, if we had an official guide, a developer could write more readable code from day one. It's really hard to train a developer to write like so. Especially after a while where their thinking settles in. I see a lot of poorly written code by junior developers where they've no idea about the value of properly formatted code.

Having such a formatting tool would be like an always-on tutor providing guidance. Of course, there are such tools but having it integrated into Swift/Xcode would be much better.

And if we have such a formatting guide, I think the Swift team should provide one specifically for the Swift Standard Library and Apple should built on top of that and provide one for their frameworks.

That being said, people will and are free to have their opinions of their own. A seasoned developer/company can have their own take on something specific. Therefore, most certainly, such a formatter must be configurable in every aspect of its.

Moreover, if that code formatter is configurable, people can easily switch other code to their style while reading them. Computers are fast and smart enough to be able to format the code to my liking when I open the file. Therefore I think with such a formatter and its configurable options, people would be happier to read someone else's code.


(Tomáš Znamenáček) #163

FWIW, the complete non-configurability of elm-format was mentioned (twice!) as one of its best features in the poll I have linked to above. I think the point is having just code as opposed to “someone’s code”.


(Roy Hsu) #164

I think having an official style guide and formatter will simplify a lot of problems and benefit the long term development.

And I'd prefer a tool with zero configuration.


(Prakash Rajendran) #165

Yes, There should be an official style guide and Yes there should be official formatting tool!

Swift is still a "new" language and an official style guide would be very helpful for new beginners as well as developers (with experience in other languages) to not get lost in "opinionated view" when it comes to style.

Formatting tool with customisable rules is the eventual next step when it comes to coding guidelines.
IIRC, Realm had their version of style guide based on GitHub's style guide and swiftlint was created shortly after that!

Today, swiftlint is the de-facto standard when it comes to styles and thanks to the customisable rules.

At a quick glance, swift-format looks lot similar.
My wish is: If swift-format somehow extends swiftlint' s rules, it would be easy for getting traction.


(David Seitz Jr) #166

Yes, an official style guide would be useful, and there should be an official formatting tool.

As many others have said, an official style guide would eliminate a lot of style arguments. While there will still be differing opinions, a standard expectation would relieve a lot of minor frustrations. People should still be allowed to configure the tool to fit their own needs and desires. An official guide and tool would create a shared starting point.


(Stern) #167

Should the Swift language adopt an official style guide and formatting tool? Yes

I've been using SwiftLint on my projects, both for formatting and to a lesser extent for linting. It definitely saves me time and having all developers on the projects I work on use it makes the code easier to read by everyone. I also try to follow the Swift API Design Guidelines when naming identifiers and methods.

I am frankly amazed when I see code posted to this forum, by people who otherwise seem to know what they're talking about, that violates the standard swift naming conventions. I'm also amazed when I see open-source projects that don't use SwiftLint.

My coding style has changed every year over the past couple decades that I've been writing code. It changed when I changed languages and OSes. It changed as each language progressed. Coding style is based in large part on the tools we use to write, edit and view code. The style developed by people who wrote on a terminal that had 80 columns and 14 lines with the predecessors to vi isn't the same style we can use with today's larger screens.

Coding style changes. The preferred rules for ivar naming in Obj-C seemed to change every year. Swiftlint already has rules to fixup antique swift coding styles like

UIColor.init(...) -> UIColor(...) and CGRectMake(...) -> CGRect(...)

I'm happy that the tool fixes up these things so I don't have to. I'm happy that it puts in the spaces and adjusts the braces so I don't have to. I want to not have to argue with anyone about the style or to have to fixup the style of another developer who can't be bothered to follow the project style.

Those of you who think that coding style is some kind of expression of your true coding self are mistaken. I just want uniformity in the projects I work on and SwiftLint gives me that. What I'd really like is a smart AI tool to write the code for me or at least to give me a smarter code review than I get from SwiftLint (or my fellow developers). Formatting the code according to a uniform style is the bare minimum of what we should all be demanding today. The smart coding assistant will have to wait.


(Thomas Roughton) #168

I think Swift should have a standard style and provide a non configurable formatter for that style guide in Swift toolchains.

I also equally think that the formatter should be externally available in a configurable form as a Swift package. In other words, development towards the formatter should progress towards a tool that most people could use to format their code in a personal style, but there should be a barrier to entry for doing so, and it should be extremely trivial to use the formatter in its default configuration.

With regards to an official style guide: I’d be cautious around calling something that. Rather, a “standard style” has the right connotations to me. I also think it’s important that the documentation for the style explains the motivations for its choices in a way that does not exclude other choices (i.e. be of the form “We chose this because” rather than “We think this is better than (other styles) because”).


(Tellow Krinkle) #169

I would be in favor of an official formatting tool as long as it's configurable.

I have a varying strength of opinion on different style points (I have no problem with either struct A: B { or struct A : B { and have used both in the past, while I much prefer tabs to spaces and soft wrap to hard wrap). For a personal project, I will happily enable a formatting tool as long as it doesn't go against style points I have strong opinions on. If it does go against any of them then I will attempt to disable those. If I still can't do that, I will stop using the formatter. Based on that, my code would be much closer to the official formatter's default style if I was able to configure it to not annoy me than if I wasn't (since I would only change the rules I cared strongly about).


(Gwendal Roué) #170

Automatic formatting can bring two kinds of annoyances: subjective and objective ones.

I don't have much to say about subjective annoyances, except that my personal experience shows that one's mind can change over time.

But there are objective annoyances, too. Those are formattings that almost always annoy almost everybody. Look, for example, at the way Xcode deals with closing closure braces when method arguments are vertically aligned :sob::

let stuff = foo(
    bar: ...,
    baz: {
        ...
}) // <- please indent

let stuff = foo(
    bar: {
        ...
}, // <- please indent
    baz: {
        ...
}) // <- please indent

So here is my take on the configurability of the formatting tool: please favor quality over configurability. I'd be very happy if the first releases of the "standard formatter" would support only one style, but produces excellent code.


(Nick Keets) #171

Something that may not be obvious to people that haven't used an automatic formatter, is that you can make it run on every file save. This allows you to not have to care about formatting details when writing code, just write a bunch of stuff, then save to format. Here is an example with Go:

gofmt


(Tony Allevato) #172

Thanks for all the feedback so far, everyone!

Since there was some concern around terms like "official" and "enforce", I've updated the proposal PR text to more clearly state that there is no intention to force a particular style on any developer and to refer to them simply as "Code Style Guidelines", analogous to "API Design Guidelines".


(Frederick Kellison-Linn) #173

I really like the updated language. It doesn't read as passing any judgement on those who may not choose to follow the style, but remains authoritative enough to communicate that this is how it "should" be done. I believe "guidelines" from the Core Team will carry enough weight that most users will be convinced to adopt the ultimate style decided upon.


(Stern) #174

Couple points: Swiftlint is agnostic on tabs vs spaces. I believe it uses whatever is already in the file if it needs to indent. It doesn't seem to me that the swift language needs to take a position on tabs vs spaces either. Although one should consider that developers that use spaces get paid more than those that use tabs.

I don't think SwiftLint has any rules on maximum line length. It does complain about long methods and long files but those are linter complaints. There's not much it could do automatically to shorten a method or file but it could hard wrap a line if it was too long. I don't particularly care about what might constitute a long line so I'd probably prefer this be configurable or opt-in but if the community chose a standard line length I would probably go with it.

Now where the braces go is a topic the formatter would certainly have to take a position on.


(Maik) #175

+1 if

  • It allows some kind of customization (e.g. disable one rule)
  • It allows „do not format this code comments“

(Tommaso Piazza) #176

• Should Swift have a built-in formatter → yes, 10,000 times yes
• Should Swift have an official, recommended style → yes
• Should the official Swift style be the only support style → no

I second @davedelong's opinions


(Jens Jakob Jensen) #177

As to

if someCondition { return }

versus

if someCondition {
    return
}

for a general style I guess we would need the expanded variant to enable setting a break point at return...

But it would be nice if the viewer (Xcode) allowed some setting to present that if-statement in the single-line variant :+1:
(Not code folding, but on-the-fly re-formatting. Possibly with jumps in line numbers)


(Grzegorz Leszek) #178

Should there be an official style? Yes!!!
Should there be an official formatting tool that enforces this style? Yes.
Should that official formatting tool be configurable? No, however there should be an option to turn off this enforcement.

Since Swift was released I was working on many different projects. All of them had a slightly different style. Aligning the style would save many debates ( like the one we have here :wink: ).

I do understand that some of us have very strong opinions about how we should write code.
That is the reason why turning off enforcement completely would make sense to me.
If one don't want to use an official guide, just use any 3rd party tool you want (or build your own).
Otherwise, what is the point of the official guide if we will be using only a subset of it?


(Frederick Kellison-Linn) #179

As a point of reference, I think that gofmt doesn’t reformat either these two examples—single statement blocks can be placed on one line or split over three. Someone more familiar with Go please correct me if I’m wrong.

EDIT: It looks like this is only true for single line functions, not blocks in general.


(Matthew Johnson) #180

Sorry for not replying sooner. It's been a busy week for me.

The reason I feel this way is because readability is extremely important to me. I don't think it's possible to anticipate in advance all of the style rules necessary to format all code in the most readable way. Even after having given style a lot of thought, I continue to occasionally run into contexts that require new nuance in style or formatting.

Any style rules that ship with the language will inherently require a long and political process to change. I think it is counterproductive to make adoption an all-or-nothing proposition. If my team wants to adopt 98% of the style rules that ship with Swift and tweak 2% of the rules we should be able to do that. I fail to see the value in the extreme rigidity of shipping a completely non-configurable tool. I don't think configuration of style rules should be required but I do think it should be possible.

I would hold this view regardless of circumstance. That said, the context for Swift is that people have written lots of Swift code and many teams are relatively happy with their existing style guidelines. Despite that, I think many of us would prefer to adopt tooling that ships with Swift if it can be tailored to work in our context. We may be willing to modify our style guidelines to match the Swift community default in some cases but there are likely to be other cases where we have good reason for not wanting to do that. Please don't put us in the position of having to make an all-or-nothing decision.

The problem is that "within reason" is both inherently subjective and also leaves a lot of room for "within reason but also very suboptimal" (which is also inherently subjective). Whatever style rules we adopt there will probably be a nontrivial subset of Swift users who feel that some of the rules are either not "within reason" or are suboptimal to the point of being undesirable. This will likely be despite the same users agreeing with the majority of the style rules we adopt. We should leave latitude for users to apply their own judgment about style on their own projects without sacrificing the ability to use the tooling that ships with Swift.

As @Paul_Cantrell mentioned upthread, Erica_Sadun's excellent book Swift Style is packed with details about the tradeoffs involved in different style choices. There is no one right answer but there are good reasons why individuals may have strong preferences for one choice or another. The idea that there should be one style to rule them all just doesn't make sense to me. Neither does the idea that Swift should ship with tooling so opinionated that it is completely unusable in projects that choose to deviate from the default style (to greater or lesser degree).

Shipping a default style should be enough for educational settings, it need not be an "official" style. The logistical aspects mostly apply at the level of individual teams. I fail to see how allowing a team to configure style rules impacts the logistical benefits. The very same logistical benefits are delivered with a custom style.

This is reasonable as a personal preference. What I don't find reasonable is shipping a tool with the language (especially at this point in Swift's evolution) that doesn't work for teams who wish to make (some) style choices of their own. I appreciate the softening of the language in the latest draft of your pitch but that doesn't really address the substance of the feedback many of us have provided.


(Tony Allevato) #181

If I'm interpreting your reply correctly, it seems as though my attempts to drill further into your rationale for configurability are being interpreted as somehow my being against configurability; I can assure you that's not the case. I'm simply trying to ensure that we get as much information about varying viewpoints during this discussion. The proposal intentionally states no position about configurability or non-configurability of an adopted format tool because, as with style guidelines, we want to answer the existential question.

On that point, however, I can offer my personal opinion: I don't think a non-configurable formatter would be well-received at all. Of the responses above where folks have said they're in favor of an adopted format tool, they're split fairly evenly between gofmt-style rigidity and having more flexibility. If this was day one in Swift, we could potentially get away with something more rigid, but for a language that already exists and has allowed individuals to develop their own style preferences, I think we need to provide ways to respect those. In addition to subjective personal preferences, there are more objective/practical reasons for needing configurability, a couple of which I mention above. That doesn't necessarily mean that we should make every single syntactic decision configurable, but we should try to identify those that matter the most to users and have allowances for them.

A configurable formatter is also just the safer option, IMO, because anyone who neither desires nor cares about configurability can just use the default configuration and leave it at that. But if we offer a non-configurable formatter, that leaves anyone who needs configurability out in the cold. It's difficult to imagine anyone saying "I won't use this formatter because it provides optional configuration settings," but it's certainly easy to imagine someone saying "I won't use this formatter because it doesn't let me configure the things I need."