Swift function compiler error 'missing return'

后端 未结 3 1835
余生分开走
余生分开走 2021-01-23 04:58

I\'ve been trying to get this function to return a Bool value but I don\'t understand why i\'m getting the error \"missing return in a function expected to return \'Bool\'. I\'v

3条回答
  •  抹茶落季
    2021-01-23 05:12

    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.


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

    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]}
    }
    

提交回复
热议问题