gpt4 book ai didi

json - 如何将(Swift4)初始化添加到可解码协议(protocol)

转载 作者:行者123 更新时间:2023-12-04 22:49:57 25 4
gpt4 key购买 nike

我正在尝试创建一个 Codable extension能够仅使用 json 字符串初始化 Decodable (Swift 4) 对象。所以应该工作的是:

struct MyObject: Decodable {
var title: String?
}

let myObject = MyObject(json: "{\"title\":\"The title\"}")

我认为这意味着我应该创建一个使用解码器调用 self.init 的 init。这是我想出的代码:
public init?(json: String) throws {
guard let decoder: Decoder = GetDecoder.decode(json: json)?.decoder else { return }
try self.init(from: decoder) // Who what should we do to get it so that we can call this?
}

该代码能够获取解码器,但在调用 init 时出现编译器错误。我得到的错误是:

'self' used before self.init call



这是否意味着无法在 Decodable 协议(protocol)中添加 init ?

完整的源代码见 codable extension on github

更新:
从@appzYourLive 调试以下解决方案后,我发现我与 init(json: 有冲突。 Decodable 和 Array 上的初始化程序。我刚刚在 GitHub 上发布了一个新版本的扩展。我还添加了解决方案作为这个问题的新答案。

最佳答案

A possible workaround



DecodableFromString

一个可能的解决方案是定义另一个协议(protocol)
protocol DecodableFromString: Decodable { }

有自己的初始化器
extension DecodableFromString {
init?(from json: String) throws {
guard let data = try json.data(using: .utf8) else { return nil }
guard let value = try? JSONDecoder().decode(Self.self, from: data) else { return nil }
self = value
}
}

符合 DecodableFromString

现在你需要让你的类型符合 DecodableFromString
struct Person:Codable, DecodableFromString {
let firstName: String
let lastName: String
}

结果

最后给出一个 JSON
let json =  """
{
"firstName": "Luke",
"lastName": "Skywalker"
}
"""

你可以建立你的值(value)
if let luke = try? Person(from: json) {
print(luke)
}

Person(firstName: "Luke", lastName: "Skywalker")

关于json - 如何将(Swift4)初始化添加到可解码协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44840474/

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