Reputation: 467
I am trying to display different data in a tableView, according to what type of user is logged in. If the typeOfUser
is set to admin, it should display certain data. If it is anything else, it should display something else.
I get the error Unexpected non-void return value in void function
on return lines inside the if typeOfUser == "admin"
.
Here is my code:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if Auth.auth().currentUser != nil {
let user = Auth.auth().currentUser!
ref.child("users").child(user.uid).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let typeOfUser = value?["typeOfUser"] as? String ?? ""
if typeOfUser == "admin" {
return self.loggedInAdminsMenu.count // ERROR HERE
} else {
return self.loggedInMenu.count // ERROR HERE
}
}) { (error) in
print(error.localizedDescription)
}
} else {
return notLoggedInMenu.count
}
}
Upvotes: 0
Views: 268
Reputation: 2415
Another Approach would be to call a function with a closure in view did load which returns you the appropriate menu count. Then reload the table view. This way is more clean and reusable.
Function
private func getMenuCountByUser(completion: @escaping (Int) ->() ) {
//your code of getting type of user
if Auth.auth().currentUser != nil {
let user = Auth.auth().currentUser!
ref.child("users").child(user.uid).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let typeOfUser = value?["typeOfUser"] as? String ?? ""
if typeOfUser == "admin" {
//return self.loggedInAdminsMenu.count // Change HERE
completion(self.loggedInAdminsMenu.count)
} else {
//return self.loggedInMenu.count // Change HERE
completion( return self.loggedInMenu.count)
}
}) { (error) in
print(error.localizedDescription)
}
Then in your viewDidLoad
getMenuCountByUser { (menuCountFromClosue) in
//reload tableView
self.menuCount = menuCountFromClosue
tableView.reloadData()
}
Note: self.menuCount is a variable which will be given to table view numberOfRowsInASection
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.menuCount
}
Hope it helps
Upvotes: 1
Reputation: 2936
In your case, you aren't returning from your function, you are returning from the closure observeSingleEvent
which is a void function. Instead, you can execute the code in viewDidLoad
and instead of returning, you can assign the value to a variable and call tableView.reloadData()
. Don't forget to also change the numberOfRows(inSection:)
function to return this newly created variable.
Upvotes: 1