测试枚举是否是集合的一部分 - 具有高性能

时间:2017-04-28 21:36:35

标签: swift

我将从网络接收许多快速状态代码。状态代码将用于通过将枚举与其rawValue匹配来初始化枚举:

enum Animal: Int {

    case cockerSpaniel = 10 //dog
    case labrador = 20 //dog
    case beagle = 30 //dog

    case hamster = 40 //rodent
    case rat = 50 //rodent
    case mouse = 60 //rodent

}

但有时我需要忽略状态代码,如果rawValue不是特定组的一部分:

enum AnimalType {
    case dog //all the rawValues associated with dogs
    case rodent //all the rawValues associated with rodents
}

是否有一些高效的机制,我可以对相关的枚举进行分组并测试从rawValue创建的枚举是否与某个组匹配?

当然,我总是可以用字典或数组做到这一点:

let dogs: [Int: Animal] = {
     var dict = [Int : Animal]()
     dict[Animal.cockerSpaniel.rawValue] = Animal.cockerSpaniel
     dict[Animal.labrador.rawValue] = Animal.labrador
     dict[Animal.beagle.rawValue] = Animal.beagle
     return dict
}()

但是后来我失去了对这组狗的实际枚举的类型检查。

1 个答案:

答案 0 :(得分:5)

如果我理解正确的问题,这就是我要做的事情:

enum Animal: Int {
    case cockerSpaniel = 10 //dog
    case labrador = 20 //dog
    case beagle = 30 //dog

    case hamster = 40 //rodent
    case rat = 50 //rodent
    case mouse = 60 //rodent

    enum AnimalGroup {
        case dog
        case rodent
    }

    var group: AnimalGroup {
        switch self {
            case .cockerSpaniel, .labrador, .beagle: return .dog
            case .hamster, .rat, .mouse: return .rodent
        }
    }
}

let statusCode = 10

 guard let animal = Animal(rawValue: statusCode) else {
    fatalError("Invalid status code")
}


if animal.group == .dog {
    print("\(animal) is a dog.")
}