如果我有一个带有原始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
从Xcode 7 beta
5(Swift版本2)开始,您现在可以默认使用来打印类型名称和枚举大小写print(_:)
,或者String
使用String
的init(_:)
初始值设定项或字符串插值语法转换为。因此,对于您的示例:
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
会导致无限递归。)
上面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)
}
有关此更改的信息,
请参见发行说明。
问题内容: 我试图从原始值获取枚举类型: 但是似乎对于带空格的字符串不起作用: 任何建议如何获得它? 问题答案: 太复杂了,只需将原始值直接分配给案例 如果案例名称与原始值匹配,您甚至可以忽略它 在Swift 3+中,所有枚举都是
但我的代码不起作用,它说类型没有定义:
我应该工作,对吧?但它不是!!!!它告诉我dbValue可以转换为RelationActiveEnum...
假设我有以下代码: 是否有一种方法可以得到下面的数组?
我想迭代一个TypeScript一个类型,并获取每个枚举的符号名,例如:
问题内容: 我遇到了这个问题,我不知道需要迭代其实际值的实际类型。 任何想法如何从enumValue中提取其可能的值? 问题答案: