在将对象附加到数组中时遇到一些问题。
我目前有
用户结构
let username: String
let uid: String
var hasFollowed: Bool = false
var posts: [Post] = [Post]()
init(uid: String, dictionary: [String: Any]) {
self.username = dictionary["username"] as? String ?? ""
self.uid = uid
}
后结构{
var id: String?
let user: User
init(user: User, dictionary: [String: Any]) {
self.user = user
}
获取用户的代码
dictionaries.forEach({ (key, value) in
guard let userDictionary = value as? [String: Any] else { return}
//creating users
var user = User(uid: key, dictionary: userDictionary)
self.users.append(user)
//fetching users posts
Database.fetchUserWithUID(uid: key, completion: { (user) in
self.fetchPostsWithUser(user: user)
})
使用uid获取用户
static func fetchUserWithUID(uid: String, completion: @escaping (User) -> Void) {
print("Fetching user with uid:", uid)
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let userDictionary = snapshot.value as? [String: Any]
else {return}
var user = User(uid: uid, dictionary: userDictionary)
completion(user)
用于附加对象的代码
var userposts = user.posts
userposts.append(post)