将两个不同的数组加载到tableview(Swift)

我有两个功能,一个可以获取我的所有帖子,另一个可以获取我正在使用Firebase提取的来宾帖子。我希望将这两个功能合并到我的表视图中。最好的方法是什么?

var postArray = [Post]() //main array that feeds into tableview
var myArray = [Post]()
var guestArray = [Post]()
var DatabaseConnect = AuthenticationService()

private func fetchAllPosts() {
    self.DatabaseConnect.fetchMyPosts {(myposts) in
        self.DatabaseConnect.fetchGuestPosts {(posts) in
            self.myArray = myposts
            self.guestArray = posts
            self.postArray = self.myArray + self.guestArray
            self.tableView.reloadData()
        }
    }
}
评论
ret
ret

这是您如何做得更好。

  1. Don't use self where it's not required. Eg: self.DatabaseConnect.
  2. Use DispatchGroup() for simultaneous API calls that are unrelated.
  3. Don't use unnecessary variables myArray and guestArray used only to append to main array why not append it directly.
  4. Use [weak self] or [unowned self] for sync background tasks.

这是代码:

var postArray = [Post]() //main array that feeds into tableview
var DatabaseConnect = AuthenticationService()

private func fetchAllPosts() {
    let group = DispatchGroup()
    postArray = []

    group.enter()
    DatabaseConnect.fetchMyPosts { [weak self] myposts in
        self?.postArray.append(contentsOf: myposts)
        group.leave()
    }

    group.enter()
    DatabaseConnect.fetchGuestPosts { [weak self] guestPosts in
        self?.postArray.append(contentsOf: guestPosts)
        group.leave()
    }

    group.notify(queue: .main) {
        self.tableView.reloadData()
    }
}
点赞
评论