gpt4 book ai didi

swift - 转换到协议(protocol)并使用值(value)?

转载 作者:行者123 更新时间:2023-11-28 16:06:42 26 4
gpt4 key购买 nike

基本上问题是代码的 RawRepresentable 部分,我需要能够获取它的值,但因为我需要转换为协议(protocol),所以它不允许我使用 rawValue。有什么解决方法吗?

public protocol Serializable {
func dictionary() -> [String: Any]
}

extension Serializable {
func dictionary() -> [String: Any] {
var result = [String: Any]()
let mirror = Mirror(reflecting: self)

for child in mirror.children {
guard let label = child.label else { continue }

switch child.value {
case let serializable as Serializable:
result[label] = serializable.dictionary()

// Compile error here
case let rawRepresentable as RawRepresentable:
result[label] = rawRepresentable.rawValue

default:
result[label] = child.value
}
}

return result
}
}

最佳答案

我认为这归结为尝试在枚举之外使用关联类型的问题。

我是这样修复的:

public protocol Serializable {
func dictionary() -> [String: Any]
}

extension Serializable {
func dictionary() -> [String: Any] {
var result = [String: Any]()
let mirror = Mirror(reflecting: self)

for child in mirror.children {
guard let label = child.label else { continue }

switch child.value {
case let serializable as Serializable:
result[label] = serializable.dictionary()

case let rawRepresentable as RawRepresentable:
let value = rawRepresentable.getValueAsAny()
result[label] = value

default:
result[label] = child.value
}
}

return result
}
}

extension RawRepresentable {
func getValueAsAny() -> Any {
return rawValue as Any
}
}

关于swift - 转换到协议(protocol)并使用值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40184720/

26 4 0
文章推荐: swift - Alamofire 对 responseJSON 的响应的具体类型是什么?
文章推荐: jquery - 缩放后 svg 过滤器在 mozilla firefox 中不起作用
文章推荐: javascript - 将
  • in
  • Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com