a protocol that implements a generic enum in swift

Here's an example of a protocol that implements a generic enum in Swift:

main.swift
enum MyEnum<T> {
    case caseOne(T)
    case caseTwo(T)
}

protocol MyProtocol {
    associatedtype EnumType
    
    func doSomething(with enumValue: EnumType)
}

struct MyStruct: MyProtocol {
    typealias EnumType = MyEnum<Int>
    
    func doSomething(with enumValue: MyEnum<Int>) {
        switch enumValue {
        case .caseOne(let value):
            print("Case one: \(value)")
        case .caseTwo(let value):
            print("Case two: \(value)")
        }
    }
}
482 chars
24 lines

In this example, we define a generic enum MyEnum, which can take any type T. We then create a protocol MyProtocol that has an associated type EnumType.

In our implementation, we define a struct MyStruct that conforms to MyProtocol. We specify that the associated type EnumType is MyEnum with type Int.

Finally, we implement the doSomething function, which takes a value of type MyEnum<Int>. We perform a pattern match on the enum and print out the corresponding value. This implementation could be customized for any type T used in MyEnum.

gistlibby LogSnag