gpt4 book ai didi

swift - 当枚举符合协议(protocol) CustomStringConvertible 时,是否可以从变量中获取枚举描述?

转载 作者:搜寻专家 更新时间:2023-10-31 22:57:46 24 4
gpt4 key购买 nike

当枚举符合协议(protocol) CustomStringConvertible 时,是否可以从变量中获取枚举描述?简化的定义是:

enum myEnum: CustomStringConvertible {

case one(p1: Int)
case two(p: CGPoint)
case aaa1
case aaa2

var description: String {
return "useless text"
}
}

没有协议(protocol)很容易:

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"

但是通过协议(protocol)我只能得到前两种情况

testCases.forEach{ 
Mirror(reflecting: $0).children.forEach{ label, value in
print( label == nil ? value : (label!, value))
}
}
=> ("one", 10), ("two", (2.0, 3.0))

因此,案例 .aaa1、.aaa2 没有 child ,所以我无法将这些案例彼此分开(当然除了 switch-case)。在当前情况下,我可以扩展该枚举的功能,但无法编辑之前完成的内容。

有没有办法获得这种情况下的一般字符串描述?

最佳答案

是的,您可以使用 Swift 的 Mirror 反射 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
}
}

关于swift - 当枚举符合协议(protocol) CustomStringConvertible 时,是否可以从变量中获取枚举描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42626323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com