Why the code block can appear both return False and True?

// using function as parameters.
func isThereAMatch(listOfNumbers: [Int], condition: (Int) -> Bool) -> Bool {
for item in listOfNumbers {
if condition(item) {
return true
}
}

return false

}

func oddNumber(number: Int) -> Bool {
return (number % 2) > 0
}

let numberList = [2, 4, 6, 7]

var isThereAMatchVar = isThereAMatch(listOfNumbers: numberList, condition: oddNumber)

print(isThereAMatchVar)
// true

As showed here.Thx~

Your code returns true, if in the list passed in at least one matches the condition (i.e. 7 matches the oddNumber condition.

If this is intended behaviour, your code works as expected. However, you probably wouldn't be asking this question if it was.

What is the intended/expected behaviour you would like to see?

1 Like

This was impossible to read, so:

// using function as parameters.
func isThereAMatch(listOfNumbers: [Int], condition: (Int) -> Bool) -> Bool {
    for item in listOfNumbers {
        if condition(item) {
            return true
        }
    }
    return false
}

func oddNumber(number: Int) -> Bool {
    return (number % 2) > 0
}

let numberList = [2, 4, 6, 7]
var isThereAMatchVar = isThereAMatch(
    listOfNumbers: numberList, 
    condition: oddNumber
)

print(isThereAMatchVar) // true

It much easier to help on a readable and highlighted piece of code.

3 Likes

Unrelated to your original problem, but this implementation is incorrect. It'll treat all negative numbers as even. (E.g. -3 % 2 is -1, which is not > 0).

The correct implementation is:

func oddNumber(number: Int) -> Bool {
    return (number % 2) != 0
}

Better yet, the standard library provides isMultiple(of:):

func oddNumber(number: Int) -> Bool {
    return !number.isMultiple(of: 2)
}
4 Likes

Back to the original question, if I understood correctly, the concern is about isThereAMatch having two return statements? If so, this return statements serve two different logical branches:

  1. If during iteration over the list of numbers, condition has returned true for an item, the function returns true and ends its execution. It might not iterate over the whole list if matching item appears early.
  2. If none of the list elements has matched the condition, first return statement would never fire and the function "fallback" to the second one.

Also, Swift has in latest versions, if I remember correctly, method on collections/sequences named contains(where:) accepting a predicate:

[2, 4, 6, 7].contains(where: { e in !e.isMultiple(of: 2) })

(good note above to use std lib method)

1 Like

Thanks for you, dears.

The Xcode told, if no 'return' in global function, would report error.