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
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]}
}
Your function does not handle case where b is an empty array. You need to define what you want the return value to be for such case, because your loop will be skipped when b is an empty array.
Secondly, your logic is also incomplete, because if the condition is good for i==0, you immediately return true, without checking the rest of the items.
Thirdly, you probably want to make sure a and b have same length.
So here is what your function should look like:
func trueSquare(a:[Int], b:[Int]) -> Bool {
if a.count != b.count {
return false
}
for i in 0..<b.count {
if b[i] != a[i]*a[i] {
return false
}
}
return true
}
I suspect the compiler requires a return value for the case when the loop is not executed at all.
Now, a ClosedRange
can never be empty, so b[0]...b.endIndex
won't ever be empty (if it results in an empty or invalid range, the code would crash), but the compiler is not smart enough to know that.
PS: Are you sure b[0]...b.endIndex
is actually the sequence you want to loop over. This creates a range from the first element of b
to the endIndex of b
. That doesn't make any sense to me.