[英]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: 你必须:
rawValue
s rawValue
的数组 maxElement
from that. maxElement
。 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.