从Xcode 7 beta 5版本开始(Swift 2),您现在可以使用
print(_:)
默认打印类型名称和枚举情况,或使用
String
的
init(_:)
初始化器或字符串插值语法转换为
String
。因此,对于您的示例:
enum City: Int {
case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne
print(city)
let cityName = "\(city)"
因此不再需要定义和维护一个方便的函数,来切换每个情况并返回字符串常量。此外,这对于任何枚举类型都可以自动工作,即使没有指定原始值类型。
可以使用 debugPrint(_:)& String(reflecting:) 来获取完全限定名称:
debugPrint(city)
let cityDebugName = String(reflecting: city)
请注意,您可以自定义每种情况下打印的内容:
extension City: CustomStringConvertible {
var description: String {
return "City \(rawValue)"
}
}
print(city)
extension City: CustomDebugStringConvertible {
var debugDescription: String {
return "City (rawValue: \(rawValue))"
}
}
debugPrint(city)
(I haven't found a way to call into this "default" value, for example, to print "The city is Melbourne" without resorting back to a switch statement. Using \(self) in the implementation of description/debugDescription causes an infinite recursion.)
上述注释指出了String的init(_:)& init(reflecting:)初始化程序打印的内容,具体取决于反映类型的遵循情况。但是,我还没有找到一种方法来调用这个“默认”值,例如打印“城市是墨尔本”,而不必回到switch语句。在实现description/debugDescription时使用\(self)会导致无限递归。
extension String {
public init<T>(_ instance: T)
public init<T>(reflecting subject: T)
}
查看发布说明了解有关此更改的信息。
print(enum)
来获取枚举类型的字符串值,你可以使用String(enum)
。 - KametrixomlocationManager didChangeAuthorizationStatus
委托回调中打印(Objective C)CLAuthorizationStatus
枚举的值,那么你需要定义一个协议扩展。例如:extension CLAuthorizationStatus: CustomStringConvertable { public var description: String { switch self { case .AuthorizedAlways: return "AuthorizedAlways" <etc> } } }
- 一旦你完成了这个步骤,它应该按照你的预期工作:print("Auth status: (\status))”。 - Goffredo