alvin123
alvin123

Reputation: 79

Return different value depends on different condition

I got following code but it gives error "Missing return in a function expected to return 'Int'" so what is the right way to write this code to give different return value depends on different if condition?

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if category == "followings"{
        return usersRealNameFollowing.count
    }
    if category == "followers"{
        return usersRealNameFollower.count
    }
}

Thanks!

Upvotes: 0

Views: 146

Answers (4)

makkhokher
makkhokher

Reputation: 238

When a function has a return type then there should be a must return statement, mean function should return something always. Now in your case you are using if statement for both return statements which means that if both statements are wrong then there will be no return value. Use if-else here that would be best option or

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
           var count: Int()
           if category == "followings"{
                count = usersRealNameFollowing.count
           }else if category == "followers"{
                count = usersRealNameFollower.count
           }
    return count
}

Upvotes: 1

Rakesh Patel
Rakesh Patel

Reputation: 1701

let’s setup the methods for rendering the table view row height

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

        if category == "followings"{
            return usersRealNameFollowing.count

        }else if category == "followers"{
            return usersRealNameFollower.count

        }else{
            return 0

        }


    }

Upvotes: 0

Paulw11
Paulw11

Reputation: 114826

You have no return statement in he case where neither if statement is true.

If there are only two options then you can just use an else statement. It would probably be better if category was an enum rather than a string since then you can be sure you have an exhaustive test using a switch

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if category == "followings"{
        return usersRealNameFollowing.count
    } else {
        return usersRealNameFollower.count
    }
}

Upvotes: 0

Pikachu620
Pikachu620

Reputation: 483

Add another return in the very end outside of any if statement.

The reason it's giving you the error is that it's possible that both if statements are false and therefore there is nothing to return!

Or maybe you could try switch

switch(catagory)
{
    case "following":
        return usersRealNameFollowing.count;
    case "followers":
        return usersRealNameFollower.count;
    default:
        return -1;   //This will catch the situations that non of the conditions are met!
}

Good luck!!!

Upvotes: 0

Related Questions