Search code examples
iosswiftgenericsassociated-types

Extension on a Generic class


I have a class

class MyClass<T> { /***/ }

which I want to extend:

extension MyClass where T: Codable & RawRepresentable & CaseIterable { /***/ }

I want to constraint the extension to RawValues of type String so I'm trying to do something like:

extension MyClass where T: Codable & RawRepresentable & CaseIterable, RawValue == String { 
   func doSomething() {
      print("doing something with strings!")
   }
}

of course this doesn't work, but is there a way to make it work?

Would be helpful to be as explicit as possible


Solution

  • Your syntax is just slightly wrong. RawValue belongs to T, so you need to reference it that way:

    extension MyClass where T: Codable & RawRepresentable & CaseIterable,
                            T.RawValue == String { ... }
                            ^^