简体   繁体   English

如何在此Swift函数中减少return false的数量

[英]How can I reduce the number of return false in this Swift func

I get the feeling all the "return false" statements in this function might be redundant. 我感到此函数中的所有“ return false”语句可能都是多余的。 I encounter a similar scenario often. 我经常遇到类似的情况。 I would like to avoid the bloat of any extra code. 我想避免任何多余代码的膨胀。

Question: Is there a way to reduce the quantity of the "return false" statements and still have the function do the same thing? 问题:有没有办法减少“ return false”语句的数量并且仍然让函数做同样的事情?

For context, I am trying to efficiently check an array of Int in UserDefaults to see if it contains a particular integer. 对于上下文,我试图有效地检查UserDefaults中的Int数组,以查看它是否包含特定的整数。

func isItemNumberInList(itemNumber : Int) -> Bool{

    if UserDefaults.standard.object(forKey: "myList") != nil{
        if var myList : [Int] = UserDefaults.standard.object(forKey: "myList") as? [Int]{
            if myList.index(of: itemNumber) != nil {
                return true
            }else{
                return false
            }
        }else{
            return false
        }
    }else{
        return false
    }

}

There is indeed a way 确实是有办法

func isDockNumberInList(dockNumber : Int) -> Bool {
    guard let myList = UserDefaults.standard.array(forKey: "myList") as? [Int],
        myList.contains(dockNumber) else { return false }
    return true
}

or 要么

func isDockNumberInList(dockNumber : Int) -> Bool {
    guard let myList = UserDefaults.standard.array(forKey: "myList") as? [Int] else { return false }
    return myList.contains(dockNumber)
}

The simplest solution is to delete your first if statement, since it is completely redundant due to the fact that the conditional binding can only succeed if the value is non-nil. 最简单的解决方案是删除您的第一个if语句,因为由于条件绑定仅在值不为nil时才能成功,所以它是完全多余的。 Then you can also merge the two inner if statement into one, since you only care whether both are true or not. 然后,您还可以将两个内部if语句合并为一个,因为您只关心两者是否为真。

func isItemNumberInList(itemNumber : Int) -> Bool{
    if let myList = UserDefaults.standard.object(forKey: "myList") as? [Int], myList.index(of: itemNumber) != nil {
       return true
    } else {
        return false 
    }
}

The else statement can be omitted is well, since in case the if statement evaluates to true, the function will exit by returning true, so the return false expression can only be reached in case the if statement before evaluated to false. else语句可以很好地省略,因为如果if语句的值为true,则该函数将通过返回true退出,因此只有在if语句之前的值为false的情况下,才能return false表达式。

func isItemNumberInList(itemNumber : Int) -> Bool{
    if let myList = UserDefaults.standard.object(forKey: "myList") as? [Int], myList.index(of: itemNumber) != nil {
       return true
    }
    return false 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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