Swift 在枚举中使用int作为大小写
我正在处理一些基本的Swift操作。使用滑块,我想指定相应的标签。由于滑块使用Swift 在枚举中使用int作为大小写,swift,enums,int,Swift,Enums,Int,我正在处理一些基本的Swift操作。使用滑块,我想指定相应的标签。由于滑块使用int表示位置,因此我将使用枚举进行转换 enum Temperature: Int { case 0 = "Zero" case 1 = "One" case 2 = "Two" case 3 = "Three" } 我想这样称呼它: variable = Temperature.0 任何帮助都是理想的。请让我知道你的想法 谢谢 枚举的原始值放在=的右侧。在枚举温度中,原始值类型为Int,
int
表示位置,因此我将使用枚举进行转换
enum Temperature: Int {
case 0 = "Zero"
case 1 = "One"
case 2 = "Two"
case 3 = "Three"
}
我想这样称呼它:
variable = Temperature.0
任何帮助都是理想的。请让我知道你的想法
谢谢 枚举的原始值放在
=
的右侧。在枚举温度
中,原始值类型为Int
,因此您可能应该这样做:
enum Temperature: Int {
case Zero = 0, One, Two, Three
}
我没有为其他情况编写原始值,因为它们可以推断
现在,您可以访问这样的案例:
Temperature.One
“但我想用整型文字来访问它!”你喊道
不幸的是,这在Swift中是不可能的。你能得到的最接近的东西是:
enum Temperature: Int {
case _0 = 0, _1, _2, _3
}
您可以使用初始值设定项初始化枚举:
Temperature(rawValue: 1)
您可以使用阵列:
let temperatures = ["Zero", "One", "Two", "Three"]
let one = temeratures[1]
或元组:
let temperatures = ("Zero", "One", "Two", "Three")
let one = temperatures.1
虽然不能在后一个使用元组中使用运行时值(非文本),但enum不用于此目的
let temperature = ("Zero", "One", "Two", "Three")
let zero = temperature.0
最好的选择我会说你使用字典:
let Temperatures:[Int: String] = [0: "zero", 1:"one"]
然后可以使用滑块值访问它。当访问字典中没有的值时,请注意->检查是否为零。您可以尝试这种方法
enum CompassPoint : Int {
case north = 0
case south = 1
case east = 2
case west = 3
}
func checkPoint(compass : CompassPoint) -> String {
switch compass {
case .east:
return "Batsman"
case .south:
return "Bowler"
case .north:
return "Wicket Keeper"
case .west:
return "All Rounder"
}}
打印(检查点(指南针:圆规点(原始值:3)!)
这里的文档:-我认为这是不可能的。这是设计的。swift中枚举中的大小写必须有名称(字符串),但不能有Int。