Swift enum with a default case

Is there a way to provide a default case enum with argument.

The output of the below code is

Example Optional("admin")
Example Optional(main.UserType.userDefault))

If I print example?.rawValue I get userDefault, however is there a way to deifine args to the type for example something like

 static var userDefault: Self(String) { get }
protocol DefaultCase: Equatable, CaseIterable, Decodable where Self: RawRepresentable {
    static var userDefault: Self { get }
}

extension DefaultCase where RawValue: Decodable, RawValue: Equatable {
    init?(rawValue: RawValue) {
        self = Self.allCases.filter { $0.rawValue == rawValue }.first ?? .userDefault
    }
    init(from decoder: any Decoder) throws {
        let container = try decoder.singleValueContainer()
        let rawValue = try container.decode(RawValue.self)
        self = .init(rawValue: rawValue) ?? Self.userDefault
    }
}

enum UserType: String, Codable, DefaultCase {
    case admin
    case user
    case userDefault
}

var example = UserType(rawValue: "admin")
print("Example \(String(describing: example?.rawValue))")

example = UserType(rawValue: "asdas")
print("Example \(example?.rawValue))")
1 Like

I'm trying to figure out if you're asking about enum cases with associated values. Can you elaborate?

(If not, this doesn't need to be restricted to enumerations.)

protocol InitializableFromAnyRawValue: RawRepresentable {
  init()
}

extension InitializableFromAnyRawValue {
  // You don't get to use the automatically-synthesized overload,
  // if you just take away failability,
  // rather than using a different signature.
  init(_ rawValue: RawValue) {
    self = .init(rawValue: rawValue) ?? .init()
  }
}

extension InitializableFromAnyRawValue where Self: Decodable, RawValue: Decodable {
  init(from decoder: any Decoder) throws {
    self.init(try decoder.singleValueContainer().decode(RawValue.self))
  }
}
extension UserType: InitializableFromAnyRawValue {
  init() { self = .userDefault }
}

A macro that adds the default case and the initializers could theoretically work, however made an issue a while ago that adding a case is currently buggy.