簡體   English   中英

Swift 5 - 枚舉內部的枚舉

[英]Swift 5 - Enum inside of enum

我正在嘗試使用枚舉對項目進行分類。 因此,我最終在枚舉中使用了枚舉。 而且我不完全確定整個枚舉是如何工作的。

但我想要做的是利用枚舉 MaterialClassification,然后如果有第二個枚舉,例如粘土,利用該枚舉的值將其作為字符串返回。

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"
        }
    }
}

我的目標是能夠在需要時返回嵌套字符串。 例如:

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

我需要一種方法來返回“初級高嶺土”。 但我不知道如何連接 2 個枚舉。

如果我正確理解您的問題,您希望訪問關聯類型的屬性。 您可以將新屬性添加到您的MaterialClassification枚舉並使用它來訪問您的案例。

像這樣的東西應該工作

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM