这是我的枚举: enum Object: Int{ case House1 = 0 case House2 = 1 var descriptor:String{ switch self{ case .House1: return "Cottage" case .House2: return "House" } }} 我想知道有没有办法让rawValue返回,如果我提供描述符
enum Object: Int{ case House1 = 0 case House2 = 1 var descriptor:String{ switch self{ case .House1: return "Cottage" case .House2: return "House" } } }
我想知道有没有办法让rawValue返回,如果我提供描述符的值?
例如,如果我的字符串是“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 } } }
现在做一些像rawVal = Object(描述符:“House”).rawValue