【问题标题】:Swift 5 - Enum inside of enumSwift 5 - 枚举内的枚举
【发布时间】:2020-10-19 02:38:43
【问题描述】:

我正在尝试使用枚举对项目进行分类。因此,我最终在枚举中使用了枚举。而且我不完全确定整个枚举是如何工作的。

但我想做的是利用枚举 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 个枚举。

【问题讨论】:

  • 你的意思是if case .clay(let clay) = materialClassification { print(clay.clayType) } else { print("not clay") }
  • @Sweeper 就是这样!谢谢! :)

标签: ios swift data-structures enums


【解决方案1】:

如果我正确理解您的问题,您希望访问关联类型的属性。您可以向 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
    }
}

【讨论】:

  • 这正是我要找的!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多