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:
rawValue
s maxElement
from that. 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.