使用PartialKeyPath
API,如何访问键路径引用的值?例如,这适用于非可选值,但不适用于Optional
值。
我遇到的问题是self[keyPath: keyPath]
返回一个非可选的Any
值。
struct Element {
let name: String
let mass: Double?
func stringValue(_ keyPath: PartialKeyPath<Element>) -> String {
let value = self[keyPath: keyPath]
switch value {
case let string as String:
return string.capitalized
case nil:
return "N/A"
case let value:
return String(describing: value)
}
}
}
let element = Element(name: "Helium", mass: 4.002602)
let string = element.stringValue(\Element.mass) /* Optional(4.002602) */
结果是case nil
从未执行,最后一种情况被打印为Optional(value)
。
如何正确解开value
以提取可选内容?
答案 0 :(得分:2)
解决方案是使用Mirror
来解开似乎不太理想的可选内容。期待在Swift中获得更好的反射支持!
func unwrap(_ value: Any) -> Any? {
let mirror = Mirror(reflecting: value)
if mirror.displayStyle != .optional {
return value
}
if let child = mirror.children.first {
return child.value
} else {
return nil
}
}
struct Element {
let name: String
let mass: Double?
func stringValue(_ keyPath: PartialKeyPath<AtomicElement>) -> String {
guard let value = unwrap(self[keyPath: keyPath]) else {
return "N/A"
}
switch value {
case let string as String:
return string.capitalized
default:
return String(describing: value)
}
}
}
let element = Element(name: "Helium", mass: 4.002602)
let string = element.stringValue(\Element.mass) /* 4.002602 */