スウィフト4のデコード可能なプロトコルの新機能を使用してRealmリストをどのように解析できるかを試しています。Decodableを使用したRealmスウィフトリスト
[{
"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"
}
]
}]
とレルムモデル::
人
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.
}
0ここで
はJSONの例であります
そして、この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
です。間違っているかもしれないもの
extension List: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
}
}
任意のアイデア:
また、私はList
によってを拡張するのですか?
EDIT
struct LoginJSON: Decodable {
let token: String
let firstCustomArrayOfObjects: [FirstCustomArrayOfObjects]
let secondCustomArrayOfObjects: [SecondCustomArrayOfObjects]
let preferences: Preferences
let person: [Person]
}
(代わりに、トークンの)各プロパティはRealm Object
のタイプであり、最後のものは、上記からの1つです。
ありがとうございます!
を。それは 'RealmSwift.List'です – Derp
@mattはい、それはカスタム' Realm'タイプです。 [Here](https://realm.io/docs/swift/latest/api/Classes/List.html)のドキュメント –
@matt Realmモデルクラスの配列として解析できないので、解析する必要がありますコード内で冗長性を持たずにdbに保存できるRealmオブジェクトx – Derp