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

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.