Avoiding `enum` across `public` API boundaries?

I think it’s a legit pattern to use if the purpose of the library creator is to provide a type with a limited number of known constructors, but that must not be switched over by clients. So, basically, an enum with suppressed switching.

But I would make it even simpler, as the internal structure is irrelevant:

public struct Planet: Sendable {
  private var name: String
  
  public static let mercury: Planet = .init(name: "mercury")
  // other cases
}

About the idea of suppressing switchability, this unfortunately doesn’t seem to work:

@available(*, deprecated, message: "DO NOT SWITCH OVER")
func ~= (pattern: Planet, value: Planet) -> Bool {
  fatalError()
}

Switching over a Planet value doesn’t produce warnings if Planet is an enum, so it’s not really overloading the default behavior, but it does work if Planet is an Equatable struct.

2 Likes