枚举enum有什么用
主要目标是通过使代码整洁有序,从而避免程序中出现不必要的相关错误。
案例
例如
var fellowRace: String = "Aragorn"
switch fellowRace {
case "Aragorn": print("Human")
case "Legolas": print("Elf")
case "Gimli": print("Dwarf")
case "Frodo": print("Hobbit")
default: print("N/A")
}
输出将是:
Human
上面的代码显然工作正常。但是在某些情况下,您可能会将“Aragorn”拼错为“Aragon”。如果您正在编写复杂的程序,在实际情况下错误输入代码是不好的。
下面是一个依赖于枚举的 switch 语句。
例如
enum fellowRace: String {
case Aragorn, Legolas, Gimli, Frodo
}
var identifyRace: fellowRace = .Aragorn
switch identifyRace {
case .Aragorn: print("Human")
case .Legolas: print("Elf")
case .Gimli: print("Dwarf")
case .Frodo: print("Hobbit")
}
原始值也可以放在枚举中以进行更深入的定制。
例如
enum fellowRace: String {
case Aragorn = "Human"
case Legolas = "Elf"
case Gimli = "Dwarf"
case Frodo = "Hobbit"
}
var identifyRace: fellowRace = .Aragorn
print(identifyRace.rawValue)
精品教程推荐
加入我们一起学习SwiftUI
QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com