Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access an enum value by its hashvalue?

Tags:

enums

swift

enum have a property named 'hashValue' which is its index inside the enum.

Now my question is, is it possible to access its value by using a number? Ex: let variable:AnEnum = 0

like image 225
Arbitur Avatar asked Sep 27 '14 17:09

Arbitur


Video Answer


3 Answers

If you want to map enum values to integers, you should do so directly with raw values. For example (from the Swift Programming Language: Enumerations):

enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

let possiblePlanet = Planet(rawValue: 7)

I don't believe there's any documentation promising that an enum's hashValue is anything in particular (if you have a link, I've be very interested). In the absence of that, you should be explicit in your assignment of raw values.

like image 58
Rob Napier Avatar answered Sep 20 '22 23:09

Rob Napier


Swift 4, iOS 12:

Simply make your enum with explicitly setting raw type (like Int in below example):

enum OrderStatus: Int {
    case noOrder
    case orderInProgress
    case orderCompleted
    case orderCancelled
}

Usage:

var orderStatus: OrderStatus = .noOrder // default value 

print(orderStatus.rawValue) // it will print 0

orderStatus = .orderCompleted
print(orderStatus.rawValue) // it will print 2
like image 36
Irfan Anwar Avatar answered Sep 20 '22 23:09

Irfan Anwar


enum Opponent: String {
   case Player
   case Computer

   static func fromHashValue(hashValue: Int) -> Opponent {
       if hashValue == 0 {
           return .Player
       } else {
           return .Computer
       }
   }

}

Explanation:

Since there is no way to get back an enum value from its hashValue, you have to do it manually. It's not pretty, but it works. You essentially create a function that allows you to pass in the index of the value you want and manually return that enum value back to the caller. This could get nasty with an enum with tons of cases, but it works like a charm for me.

like image 38
Stephen Paul Avatar answered Sep 19 '22 23:09

Stephen Paul