SE-0250: Swift Code Style Guidelines and Formatter

What is your evaluation of the proposal?

I would love to see Swift get an official formatter. The cumulative time saved trying to maintain a consistent style across a codebase/project/team/community would be a huge win. A formatter would directly lead to benefits 2, 3, and 4 in the motivation section of the proposal.

A style guide will undoubtedly end up leaving room for interpretation and would still require manual monitoring/enforcing. I'd be surprised to see it not contradict the formatter in some fringe cases. I'm not sure a guide gives any additional benefit over a formatter.

Is the problem being addressed significant enough to warrant a change to Swift?

Yes. Again, the benefits listed in the proposal can save a lot of cumulative time manually formatting and reviewing code.

Is the problem being addressed significant enough to warrant a change to Swift?

Yes. Being part of Swift would give us consistent formatting across Apple's open source Swift projects and guide newcomers to format the same way. Enabling third party formatters would not have these strong benefits.

Does this proposal fit well with the feel and direction of Swift?

Yes.

How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

A quick reading.

1 Like

To be fair, the proposal does not claim it's the best performer, simply that using SwiftSyntax is both a reliability- and performance-based decision; much of that performance will be realized with the new parsing APIs that are being introduced with (I believe) Swift 5.1.

I tried to address this in the pitch thread, but we made the conscious decision to use JSON because we wanted to avoid pulling in third-party dependencies to avoid licensing concerns at this time. So, Foundation limited us to JSON or XML. I'm quite happy to revisit decisions such as these, and I hope that they wouldn't be used as reasons to reject the work; the tool is by no means static. (I also think the "pain" of JSON is a bit overstated, IMO. I update JSON config files for Visual Studio Code much more frequently than I would update a formatter configuration, and it's never found it to be that troublesome.)

1 Like

I'm more concerned about the flexibility of the format than reading or writing, but I don't find "I do it all the time" a particularly compelling response. I mean, I have to edit plist XML files all the time, but that doesn't mean they're not a strictly inferior format and that, when I do have to edit the files, it wouldn't be much easier to read and write if they were YAML. But JSON is very limiting (or perhaps just more complex) when it comes to supporting anything that can't fit easily into a JSON type.

I also find the licensing concerns to be very strange. Could you be more specific? Swift already relies on and uses a variety of open source libraries and tools. I'd think there's a YAML library with a compatible license out there. Or is this Apple legal's concern, and not a developer concern? Swift will continue to have strictly inferior tooling if it can't use anything the community builds.

In general, I donā€™t mind if trunk snapshots include an unreleased tool, but the release snapshots should not include an unreleased tool until it will be included in an upcoming release.

I also think the sentiment expressed by @gwendal.roue is appropriate. This proposal claims to be a meta-proposal, but also proposes a specific tool that happens to be in the very early stages of development.

After reading Swift Code Formatters - NSHipster and learning more about where itā€™s at, it feels extremely preliminary to me to propose this specific tool. It looks like it has a long way to go to achieve acceptable results. Opinions may vary of course, but I find the output of Prettier to be far superior to the other tools presented by NSHipster (it actually happens to be what I would write manually modulo documentation).

Iā€™m sure your team is very capable of developing a tool every bit as good as others, but how long will that take? What if the reviews of specific style guidelines produce results you arenā€™t expecting? Is it possible this will create implementation and / or performance challenges (see the comment on NSHipster about the performance of Prettier).

It feels like we might be putting the cart before the horse by front loading official tool selection into the meta proposal. I donā€™t think itā€™s fair to call the current tool an implementation in the usual SE sense at all. An actual implementation would have to implement recommended style guidelines which donā€™t exist yet. Why not review an official tool last after all (or at least initial) style guidelines have been accepted and we can evaluate the tool against these guidelines (as well as other considerations)?

At the same time, I think itā€™s reasonable that the Swift project try to use tools that already ship with Swift in the implementation of an official formatter, which is one of the stated motivations for starting with this codebase. So I donā€™t have any objection to this codebase eventually becoming the official formatter, it just feels preliminary to be asked to evaluate whether that would be a good decision or not.

9 Likes

One option could be using Swift for configuration. swift-format can potentially share some of SwiftPMā€™s infrastructure.

5 Likes

To my knowledge, no other projects currently hosted on Apple Ā· GitHub that use SwiftPM point to package dependencies that live outside the Apple Ā· GitHub organization. Since I'm not an employee of Apple, I felt it important to not make any assumptions about what third-party libraries I could or could not use for a project that I was proposing they adopt.

If the work is adopted and those licensing concerns are not a blocking factor, then as I said, I'm more than happy to look at other options. There may be some precedent here; Apple forked cmark into swift-cmark. But understand that legally, it's not my place to make these decisions unilaterally.

Orthogonally, there's the possibility in modern package-based software development that a remote dependency you rely on can just disappear if the maintainers choose to do so. Is the risk of that happening low? Possibly. But it's still an important factor to weigh.

Thank you. That answers my question and seems reasonable.

1 Like

we have a logical twist when the tool is chosen before we know what the tool has to do.

Accepting swift-format in the swift project is about accepting a capable and malleable tool that will evolve along with the Swift style guidelines discussions. It will be conveniently available and easy to try out to see how specific rules affect the sources in your projects. We could have separate PRs for implementing particular rules for which a swift-ci invocation could create a zipped binary for mac & linux that you can use to evaluate a particular rule on your own projects.
swift-format itself will help facilitate the discussions.

Tony and his team are available to do the work for a formatter tool, written in Swift, that will adhere to the style guidelines and benefit all of the Swift community, and any interested party can help contribute as well! It is about a tool developing and evolving in the open, not about accepting a ā€˜set-in-stoneā€™ tool.
Certainly I don't think a tool written in JavaScript is what the Swift project should adopt.

7 Likes

I'm not sure why you are +1 then:

The proposal authors wish to emphasize that we are not proposing that users be required or forced to use a particular set of style conventions. The Swift compiler will not be changed in any way that would prevent otherwise syntactically valid code from compiling. Users who wish to reject the style guidelines and adopt a different style for their own projects are free to do so without the tooling pushing back on that decision.

While this does explicitly call out "tooling pushing back", I think it would still violate the spirit of this paragraph to have the community make these recommended conventions quasi-mandatory. Or am I misunderstanding the proposals intention?

3 Likes
  • What is your evaluation of the proposal?

Iā€™m very positive. I believe that this has the possibility of silencing many boring discussions about style choices (after the one big discussion has been taken in these forums).

  • Is the problem being addressed significant enough to warrant a change to Swift?

Yes, I believe so.

  • Does this proposal fit well with the feel and direction of Swift?

In the sense that similar code styles will give better readability across code bases, yes.

  • If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

NA

  • How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Iā€™ve read most posts in the pitch thread and joined the discussion. I am using existing (phenomenal) formatters and linters already, and the goal of consistency by using these are the same.

1 Like

I think the changes made during the pitch phase are great, particularly the wording around configurability, and I support the resulting proposal (with the additional in-thread clarification about what ā€œadoptingā€ swift-format means in this context). I think the concerns about configurability defeating the purpose of such a tool are overblown, and I think the default style would be widely adopted by virtue of being the default.

What is your evaluation of the proposal?

+1 -- for the style-guidelines
+1 -- for a format-tool using LibSyntax or SwiftSyntax (I don't know much about the one proposed however)

Is the problem being addressed significant enough to warrant a change to Swift?

It sounds beneficial but not urgent, so assuming development doesn't impact higher priority efforts it seems like a good addition.

Does this proposal fit well with the feel and direction of Swift?

Yes. Swift has declared itself to be opinionated. Ideally it would make adhering to its style-guidelines easy, but leave other styles possible.

Judging beauty and elegance of style is subjective, but there are big benefits if style-guidelines are predictable and consistent.

The recent embryonic discussion of Swift in a non-English language may not ever come to fruition, but it shows Swift-interest from people whose native tongue isn't English. IMHO. even before becoming fluent with Swift's keywords, predictable, consistent styling helps to visually reinforce and aid learning.

Even if you're an experienced Swift developer, consistent style-guidelines that expose an unexpected formatting can help diagnose problems with code validity.

Assuming the code is valid, predictable style-guidelines also reduce clutter and let you focus just on what the intent of the code is.

Unexpected formatting is cognitive noise, and as style-guidelines become more universally adopted, the more consistent ones expectations become, and the more cognitive-noise can be reduced.

If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

I hesitate to bring this up, but if you're familiar with the wealth of BASIC environments on old 8-bit computers (TRS-80, Apple II, etc), those are simple examples of style-guidelines that most would say were ugly, yet they were still helpful through their consistent enforcement.

The platform's style wasn't a requirement for valid entry, but the BASIC environments enforced their platform's style after entry. A motivated developer could still use other tools to develop with a different style, or toy with tricks in code to appear to vary from the platform-style. Despite those options, most programmers got quite accustomed to predictability of a platform style. So as ugly as the style was, it helped debugging because of the standardization. Even in printed magazines or books, one would find the ugly-but-predictable platform-style even when they could have changed to more attractive style-guidelines.

BASIC environments aren't terribly comparable to Swift; I merely thought it was relevant to mention the benefits effects of even an ugly set of style-guidelines.

1 Like

Thanks for pointing this out. I missed this. Theyā€™re good changes. They donā€™t include the specific case I had a colleague struggle with (when Xcode dropped support for extra spacing in its built in formatting of Objective C code), but if read as charitably as possible, it could work out. I read the overviewā€™s two bullet points - particularly the second one I quoted - as supporting a single blessed style without suggesting this configurability.

It may still be difficult for minority voices to get their needs met in the context of a voting system where majority rules. And the force of a standard enforced formatting style may be a challenge. Not sure how best to assure this other than to be welcoming to configuration additions as it evolves while still keeping a recommended default formatting configuration file.

Thank you.

  • What is your evaluation of the proposal?

    +1 -- The proposal doesn't force any use of the style but I believe having a style and tool that people can choose to ignore if they want is better than not having any at all

  • Is the problem being addressed significant enough to warrant a change to Swift?

    Yes -- Its a problem in most languages where no style guidance is proposed, everyone has their slight flavour which causes the issues described in the proposal

  • Does this proposal fit well with the feel and direction of Swift?

    Yes -- Swift, while not a simple language, is striving to make itself more accessible to a wider audience. Having taught the language to a number of people now, there is generally an issue of not understanding where spaces go, alignment of colons etc. Having a guide for this and a way to force the style if needed, helps newcomers to understand the code quicker.

  • If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

    Not in a position to answer.

  • How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

    Read through some of the original thread (it was massive so not all of it), and read through the proposal.

1 Like

I really like how the Dart team did that.
Probably we can have a look:
dart_style
Effective Dart: Style

2 Likes

What is your evaluation of the proposal?

Iā€™m in favour of it.

Is the problem being addressed significant enough to warrant a change to Swift?

Yes. The amount of time spent discussing style issues is huge and could be better invested somewhere else.

Does this proposal fit well with the feel and direction of Swift?

Yes, since Swift tries to be an opinionated language.

If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

Iā€™ve written some code in Elm that has an official, non-configurable formatter (elm-format). I wasnā€™t perfectly happy with the formatter, but at the end of the day I prefer having common code style rather than having the formatting just my way. Iā€™ve also created a poll to see how the Elm community likes the formatter ā€“ TLDR they do. (Caveat: Elm is a much simpler language, so Iā€™m not sure how much the reasoning applies.)

How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Iā€™ve tried to read as much of the discussion as humanely possible. And read the proposal, of course.

2 Likes

I'm neutral on the idea of having an official style guide and formatter. If this proposal is adopted however, I would prefer that the implementation be a somewhat configurable formatter, or if not configurable, one that only dictates a few things, while leaving more complex rules to a more powerful linter.

2 Likes
  • What is your evaluation of the proposal?

Huge +1 from my side.

  • Is the problem being addressed significant enough to warrant a change to Swift?

Yes, too much time is spent in discussing style and formatting. Developers shouldn't spend time in getting used to a new style every time they switch company or project, so I hope we can reach a point where most of the projects will simply follow the Swift Code Style Guidelines. This step would save up an enormous amount of workload both when writing and reviewing code. I think it makes sense for some dedicated people that are willing to invest time in this task to improve the future developer experience for the whole community.

  • Does this proposal fit well with the feel and direction of Swift?

Yes, it does.

  • If you have used other languages with a similar feature, how do you feel that this proposal compares to those?

I wish every language would have default style guidelines. Developers shouldn't spend time in evaluating multiple tools and configuring them, just give them what they need to do their work well.

  • How much effort did you put into your review? A glance, a quick reading, or an in-depth study?

Read the original pitch and proposal as well as the updated pitch and this discussion thread.

1 Like

I think this meta-proposal doesn't answer enough questions. But I certainly have concerns.

The ability to blend imperative, functional and mini-DSL styles is one of the biggest strengths of Swift as a modern hybrid language. Swift is not a minimalist, one-size-fits-all language like Go; pursuing a single global style would be a bad move and readability would suffer. Consider...

// Declarative
let myModel = MyModel(
   Configuration(
      a
   )
)

// Imperative
let myTableCell = MyTableCell()
myTableCell.configure(a)

// Reactive/fluent
let myDataStream = MyService()
   .configure(a)

The differences between these is not purely formatting but formatting is an essential part of each style. Having these multiple coding styles in one codebase helps. It communicates design patterns and intent through visual structure, even when there are no differences in the syntax or types involved.

And look, maybe the planned scope of swift-format is just to fix the most glaringly obvious mistakes like accidental double spaces or missing spaces around braces, while not really doing any reformatting of statement structures. In that case... whatever.

But if swift-format dooms pattern-specific styles like these, it will be a serious loss to readability.

27 Likes

Thank you for bringing up this excellent point and those examplesā€”it's something that we've put a lot of thought into. I personally do the same thing; my Package.swift files look more like your declarative example, but I would never break regular function calls that way.

The same thing can happen at a finer granularity, too. For example, even if the following wrapping would fit within the column limit:

let bounds = CGRect(
  x: someValue, y: otherValue, width: theWidth,
  height: theHeight)

It would be totally reasonable for someone to want to group the arguments like this instead:

let bounds = CGRect(
  x: someValue, y: otherValue,
  width: theWidth, height: theHeight)

swift-format handles that today by respecting existing line breaks that the user has already placed in their code, anywhere that a break would be permitted in an automatic line-wrapping situation. All three of your examples would be valid and remain untouched.

So, while we could envision a stricter approach that would canonicalize formatting by ignoring line breaks and compacting what the user has written, the examples you gave provide ample reason (IMO) that we should respect those choices.

10 Likes