gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:39:16 25 4
gpt4 key购买 nike

很抱歉这个非常基本的问题,但我想弄清楚如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com