Search code examples
swiftswift-extensions

Can you extend only RawRepresentables which use Strings for the raw value type?


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?


Solution

  • 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