预期返回“ Int”的函数中缺少返回

时间:2018-12-13 09:33:30

标签: ios swift firebase firebase-realtime-database swift4

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作为整数返回。但是我用canvasCount函数遇到了此错误“在闭合中缺少返回,期望返回'Int'”。有人可以帮我吗?

2 个答案:

答案 0 :(得分:4)

您需要完成,因为对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)
    }

}

答案 1 :(得分:2)

您可以根据需要使用completionInt

var canvasCount: Int?

func canvasCount(completion: @escaping (_ count: Int) -> Void)  {
        ref.child("Canvas").observeSingleEvent(of: .value, with: { (snapshot) in
            completion(snapshot.children.allObjects.count)
        }) { (error) in
            print(error.localizedDescription)
            completion(nil)
        }
    }

//Get the result here
//Use weak self to avoid retain cycle
canvasCount { [weak self] (count) in
        if let count1 = count {
            self?.canvasCount = count1
            DispatchQueue.main.async {
                self?.tableView.reloadData()
            }
        }
    }

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