nicklockwood / SwiftFormat

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

class with static var replaced by enum #1218

Closed technicat closed 2 years ago

technicat commented 2 years ago

Running swiftformat 0.49.12 from the shell on a file with just this

public enum TTSError: Error {}

public class TTS {
    static var ID: Int = 0
}

replaces the class with enum

public enum TTSError: Error {}

public enum TTS {
    static var ID: Int = 0
}

The key piece seems to be the static var, if that's removed, no problem

nicklockwood commented 2 years ago

This isn't a bug, it's the enumNamespaces rule.

technicat commented 2 years ago

Hmm, well, OK, not so crazy about that rule, but the whole thing is working alright as an enum (it's got some static functions in there, too). Thanks.

nicklockwood commented 2 years ago

@technicat the idea behind it is that if you are using a type purely as a namespace, it makes sense to use an empty enum, which can't be instantiated and takes up no space in memory.

But if you don't like the rule you can disable it with --disable enumNamespaces.

technicat commented 2 years ago

Just seems hackish to me to use enums not to enum (reminds me of the Java practice of using interface classes to hold constants), but that's OK, if I really want to avoid it looks like I can use class instead of static for the properties, which maybe is more appropriate anyway,.

LePips commented 2 years ago

Because Swift doesn't have namespaces, it's actually more appropriate to use an enum for the allocation reason over a class. I've done this and have worked with many who have as well.