Using Enums in associatedType

I tried to find a similar issue to find a resolution but I guess it does not exist. So, before I make a pitch for this, I wanted to see if there was something obvious that I was missing.

Consider the code,

protocol TestProtocol {
    associatedType GenericKey
    var data:[String: String] { get }
    func getData(_ key: GenericKey) -> String
}

Now, I could let this be implemented by a class or a struct, but instead I choose to create an extension like so,

func getData(_ key: GenericKey) -> String {
    return data?.filter{ $0 == key.rawValue}.first ?? ""
}

The code looks fine but has the issue that GenericKey does not have a member called rawValue
And also that it should conform to the StringProtocol as we are comparing it to a string as in $0 from a dictionary.

Strangely, I cannot have them conform to both StringProtocol and RawRepresentable at the same time using inheritance. I cannot use constraints as it is no longer considered a generic type. so what is the best way for this?

What is the best way for that? The idea is to pass a different set of Enums.

thanks,

I think you might be looking for something like this:

protocol TestProtocol {
    associatedtype GenericKey: RawRepresentable where GenericKey.RawValue == String
    var data: [String: String] { get }
    func getData(_ key: GenericKey) -> String
}

extension TestProtocol {
    func getData(_ key: GenericKey) -> String {
        return data.first { $0.0 == key.rawValue }?.value ?? ""
    }
}
3 Likes

Hi @suyashsrijan,

Thank you, I tried constraining to a protocol or type, but had not tried the second part to set a constraint on the RawRepresentable.

Thanks,