Gets an enumeration value by its hashvalue?

enum has a property called hashValue, which is its index inside the enumeration.

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

+7
enums swift
source share
2 answers

If you want to map enum values ​​to integers, you must do this directly with raw values. For example (from 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 think that there is documentation promising that enum hashValue is anything special (if you have a link, I’m very interested). In the absence of this, you must be explicit in your assignment of raw values.

+10
source share
 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 return an enum value from its hashValue, you must do this manually. This is not very, but it works. You essentially create a function that allows you to pass the index of the desired value and return that enumerated value back to the caller. This can be frustrating with a lot of cases, but for me it works like a charm.

+7
source share

All Articles