一尘不染

如何在Swift中获取枚举值的名称?

swift

如果我有一个带有原始Integer值的枚举:

enum City: Int {
  case Melbourne = 1, Chelyabinsk, Bursa
}

let city = City.Melbourne

如何将city值转换为字符串Melbourne?语言中是否可用这种类型名称自省?

类似的东西(此代码将不起作用):

println("Your city is \(city.magicFunction)")
> Your city is Melbourne

阅读 648

收藏
2020-07-07

共1个答案

一尘不染

从Xcode 7 beta
5(Swift版本2)开始,您现在可以默认使用来打印类型名称和枚举大小写print(_:),或者String使用Stringinit(_:)初始值设定项或字符串插值语法转换为。因此,对于您的示例:

enum City: Int {
    case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne

print(city)
// prints "Melbourne"

let cityName = "\(city)"   // or `let cityName = String(city)`
// cityName contains "Melbourne"

因此,不再需要定义和维护一个方便函数,该函数在每种情况下都可以打开以返回字符串文字。此外,即使未指定原始值类型,此方法也可自动用于任何枚举。

debugPrint(_:)String(reflecting:)可以用作标准名称:

debugPrint(city)
// prints "App.City.Melbourne" (or similar, depending on the full scope)

let cityDebugName = String(reflecting: city)
// cityDebugName contains "App.City.Melbourne"

请注意,您可以自定义在每种情况下打印的内容:

extension City: CustomStringConvertible {
    var description: String {
        return "City \(rawValue)"
    }
}

print(city)
// prints "City 1"

extension City: CustomDebugStringConvertible {
    var debugDescription: String {
        return "City (rawValue: \(rawValue))"
    }
}

debugPrint(city)
// prints "City (rawValue: 1)"

(我还没有找到一种方法来调用此“默认”值,例如,在不诉诸switch语句的情况下打印“城市是墨尔本”。\(self)description/
的实现中使用debugDescription会导致无限递归。)

上面Stringinit(_:)init(reflecting:)初始值设定项中的注释确切描述了打印的内容,具体取决于所反映的类型符合:

extension String {
    /// Initialize `self` with the textual representation of `instance`.
    ///
    /// * If `T` conforms to `Streamable`, the result is obtained by
    ///   calling `instance.writeTo(s)` on an empty string s.
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
    ///   result is `instance`'s `description`
    /// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
    ///   the result is `instance`'s `debugDescription`
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(reflecting: T)`
    public init<T>(_ instance: T)

    /// Initialize `self` with a detailed textual representation of
    /// `subject`, suitable for debugging.
    ///
    /// * If `T` conforms to `CustomDebugStringConvertible`, the result
    ///   is `subject`'s `debugDescription`.
    ///
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the result
    ///   is `subject`'s `description`.
    ///
    /// * Otherwise, if `T` conforms to `Streamable`, the result is
    ///   obtained by calling `subject.writeTo(s)` on an empty string s.
    ///
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(T)`
    public init<T>(reflecting subject: T)
}

有关此更改的信息,
请参见发行说明

2020-07-07