这是我的枚举:
enum Object: Int{
case House1 = 0
case House2 = 1
var descriptor:String{
switch self{
case .House1: return "Cottage"
case .House2: return "House"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道rawValue
如果我提供描述符的值,有没有办法返回?
例如,如果我的 String 是“Cottage”,我想知道 Enum 值(它应该返回 0)
我怎样才能做到这一点?
您可以为您的枚举创建一个初始化程序,它接受描述符并为其返回枚举值,然后只需调用enumValue.rawValue
. 请参阅以下内容:
enum Object: Int{
case House1 = 0
case House2 = 1
var descriptor:String{
switch self{
case .House1: return "Cottage"
case .House2: return "House"
}
}
init(descriptor: String) {
switch descriptor {
case "Cottage": self = .House1
case "House": self = .House2
default: self = .House1 // Default this to whatever you want
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在做类似的事情 let rawVal = Object(descriptor: "House").rawValue
归档时间: |
|
查看次数: |
1645 次 |
最近记录: |