无法将对象追加到数组中

时间:2018-07-22 08:05:56

标签: arrays swift

在将对象附加到数组中时遇到一些问题。

我目前有

  1. 用户结构
  2. User Struct包含一个post成员,该成员应该托管一个 帖子
  3. 帖子是我创建的另一个对象
  4. 当前,在调用firebase时,我获取了所有post对象,并尝试将它们附加到user.posts数组中。
  5. 我仔细检查了是否正确提取了post对象。
  6. 但是,userposts数组为空。

用户结构

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)

0 个答案:

没有答案