通过Swift映射将Realm对象映射到Dict

时间:2016-11-12 17:24:51

标签: swift object dictionary realm

我有两个(Realm.io)对象:

class Parent: Object {
    var title = “”
    var children = List<Child>()

    var dict: [String: Any] {
        print(“Dict 1”)
        return ([“title”: self.title, “children”: self.children.map{ $0.dict }])
    }
}

class Child: Object {
    var name = “”

    var dict: [String: Any] {
        print(“Dict 2”)
        return ([“name”: self.name])
    }
}

我正试图将它们一举转换成字典:

let parent_dict = parent.dict

它适用于“title”和其他类似的Parent属性,但实际上从未实际映射Child类对象。

以上示例的输出只是:Dict 1

1 个答案:

答案 0 :(得分:0)

请务必先将所有对象添加到域中。以下代码有效(在项目内的游乐场中尝试):

import RealmSwift

class Parent: Object {
    dynamic var title = ""
    var children = List<Child>()

    var dict: [String: Any] {
        print("Dict 1")
        return (["title": self.title, "children": self.children.map{ $0.dict }])
    }
}

class Child: Object {
    dynamic var name = ""

    var dict: [String: Any] {
        print("Dict 2")
        return (["name": self.name])
    }
}

let p1 = Parent(); p1.title = "John"
let c1 = Child(); c1.name = "Pam"
let c2 = Child(); c2.name = "Andrew"
let c3 = Child(); c3.name = "Barrack"

let realm = try! Realm()
try! realm.write {
    realm.add(p1)
    realm.add([c1, c2, c3])

    p1.children.append(objectsIn: [c1, c2, c3])
}

print(p1.dict)

运行代码后,控制台将显示:

Dict 1
["title": "John", "children": Swift.LazyMapRandomAccessCollection<RealmSwift.List<Child>, Swift.Dictionary<Swift.String, Any>>(_base: List<Child> (
    [0] Child {
        name = Pam;
    },
    [1] Child {
        name = Andrew;
    },
    [2] Child {
        name = Barrack;
    }
), _transform: (Function))]