Skip to content

Transform associated values

Giuseppe Lanza edited this page Aug 22, 2019 · 1 revision

Similarly to Optional, EnumKit offers map and flatMap functions to transform associated values, when the enum is CaseAccessible

struct Person {
    var name: String
    var lastName: String
}

enum MyEnum: CaseAccessible {
    case myString(String)
    case myInt(Int)
    case myPerson(Person)
}

let aCase: MyEnum
...

let stringValue = aCase.map(case: MyEnum.myInt) { "\($0)" } // String?
let name = aCase.map(case: MyEnum.myPerson) { $0.name } // String?
let maybeInt = aCase.flatMap(case: MyEnum.myString) { Int($0) } // Int?

These operators work exactly the same as for Optional. While Optional map and flatMap functions will invoke the transformation just when Optional case is some, the equivalent functions will invoke the transformation just if they match the specific case specified in the case parameter.