gpt4 book ai didi

swift - 使用 Decodable 的 Realm 快速列表

转载 作者:行者123 更新时间:2023-11-28 10:50:51 26 4
gpt4 key购买 nike

我正在尝试弄清楚如何使用 Swift 4 中的新功能 Decodable 协议(protocol)来解析 Realm 列表。

这是一个示例 JSON:

  [{
"name": "Jack",
"lastName": "Sparrow",
"number": "1",
"address": [
{
"city": "New York",
"street": "av. test"
}
]
},
{
"name": "Cody",
"lastName": "Black",
"number": "2"
},
{
"name": "Name",
"lastName": "LastName",
"number": "4",
"address": [
{
"city": "Berlin",
"street": "av. test2"
},
{
"city": "Minsk",
"street": "av. test3"
}
]
}]

和 Realm 模型:

public final class Person: Object, Decodable {

@objc dynamic var name = ""
@objc dynamic var lastName = ""
var address = List<Place>()

override public static func primaryKey() -> String? {
return "lastName"
}

private enum CodingKeys: String, CodingKey { case name, lastName, address}

convenience public init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.lastName = try container.decode(String.self, forKey: .lastName)
self.address = try container.decodeIfPresent(List<Place>.self, forKey: .address) ?? List()
}
}

地点

public final class Place: Object, Decodable {

@objc dynamic var city = ""
@objc dynamic var street = 0

override public static func primaryKey() -> String? {
return "street"
}
// We dont need to implement coding keys becouse there is nothing optional and the model is not expanded by extra properties.
}

解析此 JSON 的结果将是:

[Person {
name = Jack;
lastName = Sparrow;
number = 1;
address = List<Place> <0x6080002496c0> (

);
}, Person {
name = Cody;
lastName = Black;
number = 2;
address = List<Place> <0x6080002496c0> (

);
}, Person {
name = Name;
lastName = LastName;
number = 4;
address = List<Place> <0x6080002496c0> (

);

我们可以看到我们的列表总是空的。

self.address = try container.decodeIfPresent(List<Place>.self, forKey: .address) ?? List()

永远是一个nil

此外,我正在通过以下方式扩展 List:

extension List: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
}
}

任何想法可能是错误的?

编辑

struct LoginJSON: Decodable {
let token: String
let firstCustomArrayOfObjects: [FirstCustomArrayOfObjects]
let secondCustomArrayOfObjects: [SecondCustomArrayOfObjects]
let preferences: Preferences
let person: [Person]
}

每个属性(而不是 token )都是一种 Realm 对象,最后一个是上面的。

谢谢!

最佳答案

您不能直接从 JSON 转到列表。 JSON 中的内容是一个数组。所以这一行行不通:

self.address = try container.decodeIfPresent(List<Place>.self, forKey: .address) ?? List()

你必须从获取数组开始:

if let arr = try container.decodeIfPresent(Array<Place>.self, forKey: .address) {
// arr is now an array of Place
self.address = // make a List from `arr`, however one does that
} else {
self.address = nil
}

关于swift - 使用 Decodable 的 Realm 快速列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46226215/

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