且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift函数编译器错误'缺少返回'

更新时间:2022-11-11 14:14:19

如果您的数组没有元素怎么办?然后对于每个循环永远不会运行,然后您的方法将不会返回任何结果,这显然是错误的.因此,即使在循环之外,您也需要返回值.

What if your array has no element? Then for each loop never runs and then your method returns nothing which is obviously wrong. So you need to return value even outside of the loop.

但是,你的逻辑不好.您要返回布尔值,具体取决于 b 中的 first 元素是否等于 a * a .

But, your logic is bad. You're returning boolean value depending on if just first element from b is equal to a*a.

因此,逻辑应该类似于:如果每个元素都满足条件,则返回 true ,否则,返回 false .为此,在Swift 4.2+中,您可以使用方法 allSatisfy

So, logic should be something like: if every element meets the condition, then return true, otherwise, return false. To achieve this, in Swift 4.2+ you can use method allSatisfy

func trueSquare(a:[Int], b:[Int]) -> Bool {
    guard a.count == b.count else { return false } // if arrays have different number of elements, return false
    return a.enumerated().allSatisfy {$0.element * $0.element == b[$0.offset]}
}