Swift:调用Enum值转换器函数作为第一类函数

问题描述 投票:0回答:1
enum SolarSystemPlanet: String, CaseIterable {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune

    func toRawValue(_ value: SolarSystemPlanet) -> PlanetName {
        value.rawValue
    }
}

使用上面的枚举,获得行星名称数组的一种方法是调用

SolarSystemPlanet.allCases.map { $0.rawValue }

但是Swift支持一流的函数,将函数视为“一流的公民”,这使我们可以像调用任何其他对象或值一样调用函数。

因此,最好通过这个名称数组

SolarSystemPlanet.allCases.map(.toRawValue)

但是,似乎编译器需要更多上下文。它无法在编译时推断map中的类型,所以我做了

SolarSystemPlanet.allCases.map(SolarSystemPlanet.toRawValue)

编译器停止抱怨,但是我没有得到String数组。上面的行返回类型为[(SolarSystemPlanet) -> String]

的值

如果我将上面打印出来,而不是得到

["mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"]

我知道

[(Function), (Function), (Function), (Function), (Function), (Function), (Function), (Function)]

如果这样我将返回类型强制为[String]

var planets: [String] = SolarSystemPlanet.allCases.map(SolarSystemPlanet.toRawValue)

Xcode会抱怨[(SolarSystemPlanet) -> String]无法转换为[String]

毕竟有可能实现我想做的事情吗?我是否缺少某些东西或做错了什么?

并且如果不可能的话,我也将非常感谢有关原因的一些解释。

感谢您花时间阅读我的问题!

注意:这是Swift 5.1.3

swift enums coding-style first-class-functions
1个回答
0
投票
[不幸的是,(尽管很有意义,)Swift不支持将类型T的实例函数隐式转换为将R返回为闭包类型(T) -> R。其他语言,例如Java,也可以。

但是,在这种情况下,您仍然可以使用\.rawValue

keypath作为map的参数:

SolarSystemPlanet.allCases.map(\.rawValue)
这是Swift 5.2的新功能
© www.soinside.com 2019 - 2024. All rights reserved.