作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
很抱歉这个非常基本的问题,但我想弄清楚如何使用 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/
我是一名优秀的程序员,十分优秀!