使用Swift初始化一个对象以在Firebase上获取可选值

时间:2018-01-23 13:54:56

标签: ios swift firebase firebase-realtime-database initializer

我对初始化对象很满意,但我的方法似乎只有在数据库中必须存在所有参数时才能工作。我看过this哪个有效。但我现在不知道如何使用嵌套数组初始化它。

这就是我通常初始化对象的方式:

class User {

    var firstName: String
    var lastName: String
    var summary: String?
    var groups = [Group]()
    var ref: DatabaseReference?
    var key: String

    init?(from snapshot: DataSnapshot) {

        let snapshotValue = snapshot.value as? [String: Any]

        guard let firstName = snapshotValue?["firstName"] as? String, let lastName = snapshotValue?["lastName"] as? String, let summary = snapshotValue?["summary"] as? String else { return nil }

        self.firstName = firstName
        self.lastName = lastName
        self.summary = summary
        self.key = snapshot.key

        self.groups(snapshot: snapshot.childSnapshot(forPath: "groups"))

    }

    func groups(snapshot: DataSnapshot) {
        for child in snapshot.children {
            guard let group = child as? DataSnapshot else { continue }
        }
    }

1 个答案:

答案 0 :(得分:1)

只是不要让可选属性成为该防护的一部分(这就是阻止执行完成它的原因:

init?(from snapshot: DataSnapshot) {

    let snapshotValue = snapshot.value as? [String: Any]

    guard let firstName = snapshotValue?["firstName"] as? String,
          let lastName = snapshotValue?["lastName"] as? String else { return nil }

    self.firstName = firstName
    self.summary = snapshotValue?["summary"] as? String
    self.key = snapshot.key

    self.groups(snapshot: snapshot.childSnapshot(forPath: "groups"))

}

您可以选择使用if let语法:

if let summary = snapshotValue?["summary"] as? String {
    self.summary = summary
}

但在这种情况下,这更简单:

self.summary = snapshotValue?["summary"] as? String