小编典典

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

all

如果我有一个带有原始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

阅读 140

收藏
2022-07-01

共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"

所以不再需要定义和维护一个方便的函数来打开每个 case 以返回一个字符串文字。此外,即使没有指定原始值类型,这也会自动适用于任何枚举。

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

String上面的init(_:)&初始化器 的注释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)
}

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

2022-07-01