2

I'm trying to write an extension that extends enums based on strings. The way I know to extend all enumerations is to extend RawRepresentable, but I want it restricted to strings-only.

extension RawRepresentable where RawRepresentable.RawValue == String{

    func foo(){

        let myRawValue:String = self.rawValue

    }
}

So how do you specify a 'where' clause to achieve this?

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286

1 Answers1

2

To extend just RawRepresentables based on Strings, the where clause is simply where RawValue == String:

extension RawRepresentable where RawValue == String {

    func foo() {
        let myRawValue:String = self.rawValue
        print(myRawValue)
    }
}


enum Flintstone: String {
    case fred, wilma, pebbles
}

Flintstone.fred.foo()  // fred
vacawama
  • 150,663
  • 30
  • 266
  • 294