Home > OS >  generics type constraining for raw value in enums
generics type constraining for raw value in enums

Time:07-16

How can one impose the right type constraints so that raw value can be accessed?

enum SomeEnum: String, CaseIterable {
    case header = "Hello"
    case body = "How are you?"
}

func someFunc1<T: CaseIterable>(ofType: T.Type) {
    for aCase in T.allCases {
//        let someString: String = aCase.rawValue // error: Value of type 'T' has no member 'rawValue'
    }
}

func verifyLabels2<T: CaseIterable>(ofType: T.Type) {
    for aCase in T.allCases {
        let someString: String = String(describing: aCase) // wrong string! One gets "header" and "body"
    }
}

// RUN TESTS
someFunc2(ofType: SomeEnum.self)

CodePudding user response:

If the intention is that the function accepts any enumeration type whose raw value is a string then this can be achieved with

func someFunc1<T: CaseIterable & RawRepresentable>(ofType: T.Type) where T.RawValue == String {
    for aCase in T.allCases {
        let someString: String = aCase.rawValue
        print(someString)
    }
}

someFunc1(ofType: SomeEnum.self)
// Hello
// How are you?
  • Related