基于我的两(2)部分问题;起初,这只是一(1)个问题,但在Asperi为我提供了一个很好的初始阅读问题的答案后,写作部分变成了问题后,这变成了两(2)个问题。
我的答案包含了他上面的答案,然后我修改了其余的,以满足对Firebase的读写要求。
struct Post: Identifiable {
var id: String
var profile: Profile?
var uID: String
var userName: String
var text: String
var created: String
var likes: Int
var iHeight: Double
var imageName: String
init(id: String, profile: Profile, text: String, created: String, likes: Int, iHeight: Double, imageName: String ) {
self.id = id
self.profile = profile
self.userName = profile.userName
self.uID = profile.uID
self.text = text
self.created = created
self.likes = likes
self.iHeight = iHeight
self.imageName = imageName
}
init?(snapshot: DataSnapshot) {
guard
let value = snapshot.value as? [String: AnyObject],
let poster = value["poster"] as? [String: AnyObject],
let uID = poster["uid"] as? String,
let userName = poster["username"] as? String,
let text = value["text"] as? String,
let likes = value["likes"] as? Int,
let created = value["created"] as? String,
let iHeight = value["imageheight"] as? Double,
let imageName = value["imagename"] as? String
else {
return nil
}
self.id = snapshot.key
self.uID = uID
self.userName = userName
self.text = text
self.created = created
self.likes = likes
self.iHeight = iHeight
self.imageName = imageName
}
func toAnyObject() -> Any {
return [
"poster": profile!.toAnyObject(),
"text": text,
"created": created,
"likes": likes,
"imageheight": iHeight,
"imagename": imageName
]
}
}
struct Profile: Codable {
let uID: String
let userName: String
func toAnyObject() -> Any {
return [
"uid": uID,
"username": userName
]
}
}
希望这能帮助别人。