首页 > 解决方案 > 预期返回“Int”的函数中缺少返回

问题描述

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    canvasCount { (value) in
        if let res = value {
            return res
        }
    } //Missing return in a closure expected to return 'Int'
} //Missing return in a closure expected to return 'Int'

预期返回“Int”的闭包中缺少返回

func canvasCount(completion:@escaping((_ va:Int?) -> Int )) {

    ref.child("Canvas").observeSingleEvent(of: .value, with: { (snapshot) in
        completion( snapshot.children.allObjects.count)
    }) { (error) in
        print(error.localizedDescription)
        completion(nil)
    }

}

嗨,我希望能够以snapshot.children.allObjects.count整数形式返回。但是我收到了这个错误“在预期返回'Int'的闭包中缺少返回”和canvasCount函数。任何人都可以帮助我吗?

标签: iosswiftfirebasefirebase-realtime-databaseswift4

解决方案


您需要完成,因为对 firebase 的调用是异步的

func canvasCount(completion:@escaping((_ va:Int?) -> () )) { 

    ref.child("Canvas").observeSingleEvent(of: .value, with: { (snapshot) in
           completion( snapshot.children.allObjects.count)
    }) { (error) in
        print(error.localizedDescription)
           completion(nil)
    }

}

canvasCount { (value) in 
   if let res = value {
      print(res)
   }
}

编辑: ------------------------------------------------ -

声明一个实例变量

var counter = 0

内嵌viewDidLoad

canvasCount { (value) in
  if let res = value {
     self.counter =  res
     self.tableView.reloadData()
  }
} 

然后复制那些

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return counter
} 


func canvasCount(completion:@escaping((_ va:Int?) -> ())) {

    ref.child("Canvas").observeSingleEvent(of: .value, with: { (snapshot) in
        completion( snapshot.children.allObjects.count)
    }) { (error) in
        print(error.localizedDescription)
        completion(nil)
    }

}

推荐阅读