Swift enum both a string and an int

With Swift 4.2 this can be done using CaseIterable. One, relatively concise way is to do the following

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"

I think this will do it for me. Thank you self.. :)

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"
      }
   }
}

Tags:

Enums

Swift