简体   繁体   中英

Access rawValue of enum in array in Swift

I'm trying to use maxElement to work with enums in an array, accessed by .rawValue as shown in the example below:

var planets: [Planets] = [.Mars, .Earth, .Jupiter]
maxElement(planets.rawValue)

I could just use other methods to get the max rawValue but it would be so nice and easy if it could be used this way, but is it even possible?

There is no direct way to that.

let maxPlanet = Planets(rawValue: maxElement(planets.map({$0.rawValue})))!

You have to:

  1. make an array of rawValue s
  2. get maxElement from that.
  3. convert back to enum using Planets(rawValue:)

Conform to Comparable protocol to use maxElement with your enum.

enum Planets: Int, Comparable {
    case Earth, Mars, Jupiter
}

func <(lhs: Planets, rhs: Planets) -> Bool {
    return lhs.rawValue < rhs.rawValue
}

Then

let planets: [Planets] = [.Mars, .Jupiter, .Earth]
let maxPlanet = maxElement(planets) // .Jupiter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM