我对初始化对象很满意,但我的方法似乎只有在数据库中必须存在所有参数时才能工作。我看过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 }
}
}
答案 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