How to get the name of enumeration value in Swift?

前端 未结 12 1450
太阳男子
太阳男子 2020-11-29 23:53

If I have an enumeration with raw Integer values:

enum City: Int {
  case Melbourne = 1, Chelyabinsk, Bursa
}

let city = City.Melbourne
         


        
12条回答
  •  粉色の甜心
    2020-11-30 00:57

    There is no introspection on enum cases at the moment. You will have to declare them each manually:

    enum City: String, CustomStringConvertible {
        case Melbourne = "Melbourne"
        case Chelyabinsk = "Chelyabinsk"
        case Bursa = "Bursa"
    
        var description: String {
            get {
                return self.rawValue
            }
        }
    }
    

    If you need the raw type to be an Int, you will have to do a switch yourself:

    enum City: Int, CustomStringConvertible {
      case Melbourne = 1, Chelyabinsk, Bursa
    
      var description: String {
        get {
          switch self {
            case .Melbourne:
              return "Melbourne"
            case .Chelyabinsk:
              return "Chelyabinsk"
            case .Bursa:
              return "Bursa"
          }
        }
      }
    }
    

提交回复
热议问题