使用 Swift 初始化对象以在 Firebase 上采用可选值
Initialize an object to take in optional values on Firebase with Swift
一般来说,我对初始化对象很满意,但我的方法似乎只在所有参数都必须存在于数据库中时才有效。我看过 哪个有效。但是我现在不知道如何用嵌套数组来初始化它。
这是我通常初始化对象的方式:
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 }
}
}
只是不要让可选属性成为该守卫的一部分(这就是阻止执行完成它的原因:
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
一般来说,我对初始化对象很满意,但我的方法似乎只在所有参数都必须存在于数据库中时才有效。我看过
这是我通常初始化对象的方式:
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 }
}
}
只是不要让可选属性成为该守卫的一部分(这就是阻止执行完成它的原因:
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