Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generics type constraining for raw value in enums

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading