简体   繁体   中英

Swift 5 - Enum inside of enum

I'm trying to use enum to classify items. As such, I've ended up with having enums inside of enums. And I'm not entirely sure on how this whole enum thing works.

But what I want to do is tap into the enum MaterialClassification, and then if theres a second enum, like in case clay, tap into that enum's value to return it as a string.

enum MaterialClassification {
    
    case clay(value: Clay)
    case flux//(value: Fluxs)
    case glassFormer
    case stain//(value: Clay)
    case accessoryMaterial
    
    case all//(value: Clay)
}

extension MaterialClassification {
    var materiaIdentifier: String {
        switch self {
        case .clay:
            return "clay"
        case .flux:
            return "flux"
        case .glassFormer:
            return "glassFormer"
        case .stain:
            return "stain"
        case .accessoryMaterial:
            return "accessoryMaterial"
        case .all:
            return "all"
        }
    }
}
enum Clay {
    
    case iskaolin// = "Kaolin"
    case isPrimaryKaolin// = "Primary Kaolin"
    case isSecondaryKaolin //= "Secondary Kaolin"
    case isBallClay //= "Ball Clay"
    case isStoneware// = "Stoneware"
    case isFireClay //= "Fire Clay"
    case isEarthenware// = "Earthenware"
    case isVolcanicClay// = "Volcanic"
}

extension Clay {
    
    var clayType: String {
        switch self {
        case .iskaolin:
            return "Kaolin"
        case .isPrimaryKaolin:
            return "Primary Kaolin"
        case .isSecondaryKaolin:
            return "Secondary Kaolin"
        case .isBallClay:
            return "Ball Clay"
        case .isStoneware:
            return "Stoneware"
        case .isFireClay:
            return "Fire Clay"
        case .isEarthenware:
            return "Earthenware"
        case .isVolcanicClay:
            return "Volcanic Clay"
        }
    }
}

My goal is to be able to return the nested string when needed. For example:

materialClassification: MaterialClassification.clay(type: Clay.isPrimaryKaolin)

I need a way to return "Primary Kaolin". But I can't figure out how to connect the 2 enums.

If I understand your question correctly, you want to access associated types' properties. You can add a new property to your MaterialClassification enum and use it to access your cases.

Something like this should work

var type: String? {
    
    switch self {
    case .clay(let clay):
        return clay.clayType
    case .flux(let flux):
        return flux.fluxType
    case .stain(let stain):
        return stain.stainType
    case .glassFormer, .accessoryMaterial, .all:
        return nil
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM