简体   繁体   English

在Swift中访问数组中枚举的rawValue

[英]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: 我正在尝试使用maxElement处理数组中的枚举,可通过.rawValue访问,如以下示例所示:

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? 我可以使用其他方法来获取最大rawValue,但是如果可以通过这种方式使用它将会非常容易,但是有可能吗?

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 制作rawValue的数组
  2. get maxElement from that. 从中获取maxElement
  3. convert back to enum using Planets(rawValue:) 使用Planets(rawValue:)转换回枚举

Conform to Comparable protocol to use maxElement with your enum. 符合Comparable协议以将maxElement与您的枚举一起使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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