返回不同的值取决于不同的条件

时间:2018-02-27 03:48:31

标签: ios swift uitableview

我得到了以下代码,但它给出了错误"在预期返回的函数中缺少返回' Int'" 那么,编写此代码以获得不同返回值的正确方法取决于不同的if条件?

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

谢谢!

3 个答案:

答案 0 :(得分:0)

在任何if语句之外的最后添加另一个返回。

它给你错误的原因是两个if语句都可能是假的,因此没有任何东西可以返回!

或许您可以尝试切换

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!
}
祝你好运!!!

答案 1 :(得分:0)

if陈述都不成立的情况下,您没有退货声明。

如果只有两个选项,那么您可以使用else语句。如果categoryenum而不是字符串可能会更好,从那以后您可以确定使用switch进行详尽的测试

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

答案 2 :(得分:0)

让我们设置渲染表格视图行高的方法

 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

        }


    }