从 Xcode 7 beta 5(Swift 版本 2)开始,您现在可以默认使用 print(_:) 打印类型名称和枚举大小写,或者使用 String 的 init(_:) 初始化程序或字符串插值语法转换为 String .所以对于你的例子:
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)"
(我还没有找到一种方法来调用这个“默认”值,例如,打印“The city is Melbourne”而不求助于 switch 语句。在实现中使用\(self) description/debugDescription 导致无限递归。)
String 的 init(_:) 和 init(reflecting:) 初始化器上面的 cmets 准确描述了打印的内容,具体取决于反射类型符合的内容:
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)
}
有关此更改的信息,请参阅 release notes。