我有一种情况,我正在尝试对某些数据进行二进制解码,数据类型同时具有数值和字符串值以及名称.我正在考虑使用如下的枚举:
enum TARGET_TRACK_TYPE : String {
case TT_INVALID = "Invalid"
case TT_TRUE_TRACK_ANGLE = "True Track Angle"
case TT_MAGNETIC = "Magnetic"
case TT_TRUE = "True"
}
Run Code Online (Sandbox Code Playgroud)
但是我也知道:
TT_INVALID = 0并且TT_TRUE_TRACK_ANGLE = 1,等有没有一种简单的方法来封装这两个"东西"的字符串和数值到枚举结构或做我需要做某种结构的/类来处理呢?
我想我想做点什么
let a = TARGET_TRACK_TYPE.rawValue(value: 2)
println(a)
哪个会打印 True Track Angle
同样,我知道这可以用结构或类来完成,但我对枚举特别感兴趣
或者换个例子:
/// Emitter Category is defined in section 3.5.1.10 of the GDL90 Spec
struct EmitterCategory {
let category : Int
func getString() -> String {
switch(category) {
case 0:
return "No aircraft type information";
case 1:
return "Light";
case 2:
return "Smalle";
case 3:
return "Large";
case 4:
return "High Vortex Large";
case 5:
return "Heavy";
case 6:
return "Highly Manuverable";
case 7:
return "Rotorcraft";
case 8:
return "(Unassigned)";
case 9:
return "Glider/sailplane";
case 10:
return "Ligther than air";
case 11:
return "Parachutist/sky diver";
case 12:
return "Ultra light/hang glider/paraglider";
case 13:
return "(Unassigned)";
case 14:
return "Unmanned aerial vehicle";
case 15:
return "Space/transatmospheric vehicle";
case 16:
return "(Unassigned)";
case 17:
return "Surface vehicle - emergency vehicle";
case 18:
return "Surface vehicle - service vehicle";
case 19:
return "Point obstacle";
case 20:
return "Cluster Obstacle";
case 21:
return "Line Obstacle";
default:
return "(reserved)";
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将这个结构重构为一个枚举,以便我用一个整数值构造枚举,但我"读取"枚举为一个字符串?我很确定答案是否定的.
Jee*_*eef 32
我想这会为我做.谢谢你自己.. :)
protocol GDL90_Enum {
var description: String { get }
}
enum TARGET_ADDRESS_TYPE : Int, GDL90_Enum {
case ADSB_ICAO_ADDRESS = 0
case ADSB_SELF_ADDRESS = 1
case TISB_ICAO = 2
case TISB_TRACK_ID = 3
case SURFACE_VEHICLE = 4
case GROUND_STATION = 5
var description: String {
switch self {
case .ADSB_ICAO_ADDRESS:
return "ADS-B with ICAO address"
case .ADSB_SELF_ADDRESS:
return "ADS-B with Self-assigned address"
case .TISB_ICAO:
return "TIS-B with ICAO address"
case .TISB_TRACK_ID:
return "TIS-B with track file ID"
case .SURFACE_VEHICLE:
return "Surface Vehicle"
case .GROUND_STATION:
return "Ground Station Beacon"
default:
return "Reserved"
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
使用Swift 4.2可以使用CaseIterable完成。一种相对简洁的方法是执行以下操作
enum Directions: String, CaseIterable {
case north, south, east, west
static var asArray: [Directions] {return self.allCases}
func asInt() -> Int {
return Directions.asArray.firstIndex(of: self)!
}
}
print(Directions.asArray[2])
// prints "east\n"
print(Directions.east.asInt())
// prints "2\n"
print(Directions.east.rawValue)
// prints "east\n"
Run Code Online (Sandbox Code Playgroud)