Swift 当枚举符合协议CustomStringConverable时,是否可以从变量中获取枚举描述?
当枚举符合协议CustomStringConverable时,是否可以从变量中获取枚举描述?简化定义为:Swift 当枚举符合协议CustomStringConverable时,是否可以从变量中获取枚举描述?,swift,reflection,enums,swift3,Swift,Reflection,Enums,Swift3,当枚举符合协议CustomStringConverable时,是否可以从变量中获取枚举描述?简化定义为: enum myEnum: CustomStringConvertible { case one(p1: Int) case two(p: CGPoint) case aaa1 case aaa2 var description: String { return "useless text" } } 没有协议很容易: let testCases = [en
enum myEnum: CustomStringConvertible {
case one(p1: Int)
case two(p: CGPoint)
case aaa1
case aaa2
var description: String {
return "useless text"
}
}
没有协议很容易:
let testCases = [en.one(p1: 10), en.two(p: CGPoint(x: 2, y: 3)), en.aaa1, en.aaa2]
testCases.forEach{
print( String(reflecting: $0 ), terminator: "\t\t" )
}
=> "en.one(10) en.two((2.0, 3.0)) en.aaa1 en.aaa2"
但根据协议,我只能得到前两个病例
testCases.forEach{
Mirror(reflecting: $0).children.forEach{ label, value in
print( label == nil ? value : (label!, value))
}
}
=> ("one", 10), ("two", (2.0, 3.0))
因此,cases.aaa1、.aaa2没有孩子,所以我无法将这些cases彼此分开(当然,除了switch case)。在当前情况下,我可以扩展该枚举的功能,但不能编辑以前所做的操作
有没有一种方法可以获得这种情况下的一般字符串描述 是的,您可以使用Swift的镜像反射API。实例的枚举大小写列为镜像的子对象,您可以按如下方式打印其标签和值:
extension myEnum {
var description: String {
let mirror = Mirror(reflecting: self)
var result = ""
for child in mirror.children {
if let label = child.label {
result += "\(label): \(child.value)"
} else {
result += "\(child.value)"
}
}
return result
}
}
也许上面不清楚,但要求如下:1。描述是遗留属性,无法更改其逻辑2。我需要得到类似于调试器描述的“字符串描述”。例如:“en.aaa1”“en.aaa2”“en.two((2.0,3.0))”等,当然每个情况下不使用开关:)