nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.9k stars 639 forks source link

Struct within struct changes to enum with Format File from Xcode #1130

Closed JulesMoorhouse closed 2 years ago

JulesMoorhouse commented 2 years ago

When I have the following...

struct Default {
    struct Sensible {
        static let amount: NSDecimalNumber = 1
   }
}

Then I use Xcode > Editor > SwiftFormat > Format File, the following is produced, notice the struct inside struct to changed to an enum.

struct Default {
    enum Sensible {
        static let amount: NSDecimalNumber = 1
   }
}

As a workaround I've setup a .swiftformat file to ignore this file, which I've placed in the folder where the file lives...

--exclude Default.swift

I've also tried adding this file to the same level as the project with...

--exclude **/Default.swift

However, I'm guessing Format File ignores the .swiftformat file.

EDIT: I have version 0.49.2 of SwiftFormat

nicklockwood commented 2 years ago

@JulesMoorhouse this is deliberate. It's done by the enumNamespaces rule, which you can disable with:

--disable enumNamespaces
nicklockwood commented 2 years ago

@JulesMoorhouse sorry, I didn't notice you're using the Xcode extension. For sandboxing reasons the extension can't read the file system, so it doesn't see the .swiftformat config (although there should be a fix for that in the next release).

For now you'll have to disable the rule inside the extension app itself.

JulesMoorhouse commented 2 years ago

Ok, thanks, I’ll try that.

Can I ask what the benefit is in that change to the code?

nicklockwood commented 2 years ago

In cases like this, where you are using the struct purely as a namespace, an empty enum has the semantic advantage that it can't be instantiated. It wouldn't ever be meaningful to write:

let sensibleStruct = Default.Sensible()

but nothing actually prevents you from doing it. With an enum however, this wouldn't compile.