简体   繁体   中英

Unexpected non-void return value in void function in Swift using numberOfRowsInSection

This question has already been asked numerous times, but nothing seems to be working in my particular case. As you can see in my code below, I have created an extension of my View Controller for my UITableViewDataSource. I am trying to pull information from my Firebase Realtime Database and depending on what I get, return a certain Int. The issue is that whenever I try and return an Int from within the Firebase Snapshot, I receive this error: "Unexpected non-void return value in void function." I understand the reason for this, but I am not sure how I can make my code work. Any solutions?

My code:

extension LikeOrDislikeViewController: UITableViewDataSource {

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

        let uid  = Auth.auth().currentUser?.uid

        Database.database().reference().child("Num Liked").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
            if let dictionary = snapshot.value as? [String: AnyObject] {
                let numMoviesLiked = ((dictionary["Number of Movies Liked"] as? Int))!

                if numMoviesLiked%4 == 0 {
                    return numMoviesLiked/4
                }
            }
        })
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell()
        cell.backgroundColor = UIColor.red
        tableView.rowHeight = 113
        cell.textLabel?.text = "\(indexPath.row)"

        return cell
    }
}

Your problem is this return numRows inside the database block , it doesn't consider to return any values , also the call is asynchronous so don't expect it to finish before the return 10 of numberOfRowsInSection , completely remove this part and put it inside viewDidLoad

Database.database().reference().child("Num Liked").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
    if let dictionary = snapshot.value as? [String: AnyObject] {
        let numMoviesLiked = ((dictionary["Number of Movies Liked"] as? Int))!

        if numMoviesLiked/4 == 0 {
            numRows = numMoviesLiked/4
            self.tableView.reloadData()
        }
    }
})

logically if you do if only when you compare numMoviesLiked/4 == 0 then numRows will be always 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM