I'm confused how to consistently format Swift code

Hi,

I’ve been trying to find a consistent way to format my code, but I’m confused how it all works…

Is there a way to format code from command line in the same way Xcode (Format file with ‘swift-format’) or VS Code (Shift+Option+F) format the code? For example, here is some code formatted by Xcode/VS Code:

struct Item {
    let id: String
}

Now, if I try to run the swift format . --recursive --in-place command, the number of spaces is different:

struct Item {
  let id: String
}

This is annoying, because when I try to reformat all my code, the indentation changes everywhere. I can see that Xcode mentions formatting code with ‘swift-format’ as oppose to ‘swift format’, but I don’t really know what the difference is - and relying on Google or even AI to explain this is very hard, because the name is pretty much the same.

Have you tried using a configuration file

2 Likes

swift-format and swift format are just two different ways of spelling the same command. There is another thing that is actually different though, and that's SwiftFormat in PascalCase.

I love the icon/logo there! I didn't know we had an ASCII Swift emoji =}

What about PascalCase - I hope this is configurable.

Yes, they have a "Configuration" section in the README.

I believe they meant that the name of SwiftFormat, the non-Apple-official tool built by Nick Lockwood, is spelled in Pascal case, otherwise known as upper camel case.

2 Likes