如何Int在 Swift 中使用多个 Enum 类型的原始值?我收到此错误:
枚举“case”声明中逗号后的预期标识符。
就我而言,我希望onGoingcase 接受多个Int原始值,以便代码可以相应地返回状态。
enum STATUS_CODE : Int {
case onGoing = 5, 50,70, 90
case atWorkshop = 10
case completed = 16
case comedy = 35
case crime = 80
case NoDate = 0
func getString() -> String {
switch self {
case .onGoing : return "New order"
case .atWorkshop: return "At workshop"
case .completed : return "Animation"
case .comedy : return "Comedy"
case .crime : return "Crime"
case .NoDate : return "No Order"
}
}
}
Run Code Online (Sandbox Code Playgroud)
Enumcase 不能有多个 rawValues。因为想象你这样称呼:
print( STATUS_CODE.onGoing.rawValue )
Run Code Online (Sandbox Code Playgroud)
您期望打印什么值?
相反,您可以拥有一个像您想到的那样的自定义枚举:
enum STATUS_CODE: RawRepresentable {
init(rawValue: Int) {
switch rawValue {
case 5, 50,70, 90: self = .onGoing(rawValue)
case 10: self = .atWorkshop
case 16: self = .completed
case 35: self = .comedy
case 80: self = .crime
case 0: self = .NoDate
default: self = .unknown(rawValue)
}
}
var rawValue: Int {
switch self {
case .onGoing(let rawValue): return rawValue
case .atWorkshop: return 10
case .completed: return 16
case .comedy: return 35
case .crime: return 80
case .NoDate: return 0
case .unknown(let rawValue): return rawValue
}
}
case onGoing(Int)
case atWorkshop
case completed
case comedy
case crime
case NoDate
case unknown(Int)
func getString() -> String {
switch self {
case .onGoing : return "New order"
case .atWorkshop: return "At workshop"
case .completed : return "Animation"
case .comedy : return "Comedy"
case .crime : return "Crime"
case .NoDate : return "No Order"
case .unknown(let rawValue): return "Unknown \(rawValue)"
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然,这是一个演示,可以重构;)