a protocol that implements a generic enum variable in swift

To create a protocol that implements a generic enum variable in Swift, you can use the following code:

main.swift
protocol EnumProtocol {
    associatedtype CustomEnum: RawRepresentable where CustomEnum.RawValue == String
    var myEnum: CustomEnum { get set }
}

enum MyEnum: String {
    case optionOne = "Option One"
    case optionTwo = "Option Two"
}

struct MyStruct: EnumProtocol {
    var myEnum: MyEnum
}
300 chars
14 lines

In the code above, we first define a protocol called EnumProtocol. This protocol has an associated type called CustomEnum. The CustomEnum must conform to the RawRepresentable protocol, where the RawValue is of type String. The EnumProtocol also includes a variable called myEnum, which is of the associated type CustomEnum and must be get and set.

We then define an enum called MyEnum. This enum has two cases, optionOne and optionTwo, and the raw value of each case is a String.

Lastly, we create a struct called MyStruct that conforms to the EnumProtocol. We set the myEnum variable to be of type MyEnum.

This protocol can now be used to create custom classes or structures that include an enum variable with a generic type.

gistlibby LogSnag