swift - 如何将带有枚举的开关用于字符串

标签 swift

很抱歉这个非常基本的问题,但我想弄清楚如何使用 switch 语句来检查它是否是某个字符串。

例如,如果我有一个 AnimalType 枚举,然后我有一个动物结构:

enum AnimalType: String {
   case Mammal = "Mammal"
   case Reptile = "Reptile"
   case Fish = "Fish"
}

struct Animal {
   let name: String
   let type: String
}

如果我想遍历 Animals 列表然后有一个 switch 语句,我将如何将 Animal.Type 字符串与枚举相匹配?我也不想将 Animal 结构更改为 let type: AnimalType。

switch Animal.type {
case :
...// how do I match the string to the enum?

最佳答案

您可以从字符串 rawValue 创建一个动物类型并打开它: 但首先我会将大小写更改为小写,这是 Swift 中的首选样式。

func checkType(of animal: Animal) {
    guard let animalType = AnimalType(rawValue: animal.type) else {
        print("Not an animal type")
        return
    }
    switch animalType {
    case .mammal: break
    case .reptile: break
    case .fish: break
    }
}

或者,您也可以打开字符串并比较它是否与您的任何 AnimalType rawValues 匹配:

func checkType(of animal: Animal) {
    switch animal.type {
    case AnimalType.mammal.rawValue: break
    case AnimalType.reptile.rawValue: break
    case AnimalType.fish.rawValue: break
    default:
        print("Not an animal type")
        break
    }
}

关于swift - 如何将带有枚举的开关用于字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49345075/

相关文章:

ios - Swift 2.1 - 在委托(delegate)方法调用上展开 Optional 时意外发现 nil

ios - 如何让 NSBatchDeleteRequest 删除并允许您再次添加回对象

ios - 在模拟器中运行 Apple Watch glance 应用程序时出现问题

ios - 如何修复 Xcode 中的 '_sqlite3_prepare_v3' 链接器错误

swift - 如何在场景转换尝试中处理 "no scene"?

ios - Sprite Kit 中的增量分数显示在 HUD 中

ios - 动画 UIButton 的文本以捏合和捏开不起作用

iOS - 将 CAGradientLayer 集中到父 UIView

ios - 迪尔德 : Symbol not found: __TMPdCSs12AnyGenerator

ios - 调整 NSMutableAttributedString 的字体大小与 UILabel 的框架高度成比例