Swift NumberOfRowsInSection无效函数中意外的非无效返回值

Swift NumberOfRowsInSection无效函数中意外的非无效返回值,swift,firebase,firebase-realtime-database,tableview,Swift,Firebase,Firebase Realtime Database,Tableview,我试图显示或不显示我的“NoPostsView”,这取决于我的firebase数据库 这就是我发现是否有帖子的功能: func checkIfPostsExists(YES: @escaping () -> Void, NO: @escaping () -> Void) { REF_POSTS.observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.exi

我试图显示或不显示我的“NoPostsView”,这取决于我的firebase数据库

这就是我发现是否有帖子的功能:

func checkIfPostsExists(YES: @escaping () -> Void, NO: @escaping () -> Void)
{
     REF_POSTS.observeSingleEvent(of: .value, with:
     {
         (snapshot) in
         if snapshot.exists()
         {
             YES()
         }
         else
         {
             NO()
         }
     })
}
我就是这样使用它的:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    checkIfPostsExists(YES:
    {
        if self.posts.count <= 0
        {
            return 7 // ERROR IS IN THIS LINE
        }
        else if self.posts.count != 0
        {
            self.noPostsView.isHidden = true
        }
    })
    {
        self.noPostsView.isHidden = false
    }
    return posts.count
}
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int
{
检查性别歧视者(是:
{

如果self.posts.count您应该能够执行以下操作

// uses a completion with a boolean value to show whether has posts or not
private func hasPosts(completion: (Bool) -> Void) {
    // check posts and then at some point return a boolean
    completion(true) 
}

// check if has posts and either show tableView or noPostsView
override func viewDidLoad() {
   super.viewDidLoad() 

   hasPosts() { hasPosts in 
      if hasPosts {
          tableView.dataSource = self
          // maybe other logic
      }
      noResultsView.isHidden = hasPosts
      tableView.isHidden = !hasPosts
   }
} 

闭包被定义为
@转义()->Void
这意味着它不带任何参数,也不返回任何内容。如果checkIfPostsExists函数执行类似于访问网络或从数据库中读取的操作,那么它将始终返回帖子。count谢谢。但是我应该怎么做呢?首先详细解释一下,
checkIfPostsExists
的具体功能是什么?我有函数。它所做的只是访问数据库并检查给定的子项是否存在。我不能完全理解为什么使用闭包来做这件事。如果你想检查是否存在某些东西,然后使tableView基于此运行,你可以使用基于条件的重新加载数据谢谢,但这样我仍然无法返回n有些事情你不能只从异步函数返回。异步函数需要时间,因此你的函数在完成之前返回。因此你使用完成处理程序“在任务完成后做一些工作”。使用上面的例子,当你加载VC时,你检查你是否有帖子,然后加载
tableView
noPostsView
。按照您的操作方式,
返回posts.count
在访问数据库之前返回,但即使没有任何posts,我仍希望显示tableView。这可能吗?当然可以,只需更改逻辑,您可以查看另一个答案,了解有关“从异步函数返回”的更多信息:或者可能是be可以在
numberofrowsinssection
功能之外更改tableView的行数