How to require an enum be defined in Swift Protocol

Protocols can have associatedtypes which would just need to be adhered to in any subclass:

enum MyEnum: String {
    case foo
    case bar
}

protocol RequiresEnum {
    associatedtype SomeEnumType: RawRepresentable where SomeEnumType.RawValue: StringProtocol

    func doSomethingWithEnum(someEnumType: SomeEnumType)
}

class MyRequiresEnum: RequiresEnum {
    typealias SomeEnumType = MyEnum

    func doSomethingWithEnum(someEnumType: SomeEnumType) {
        switch someEnumType {
        case .foo:
            print("foo")
        case .bar:
            print("bar")
        }
    }
}

let mre = MyRequiresEnum()
mre.doSomethingWithEnum(someEnumType: .bar)

Edit: The associatedtype must be adhered to

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)