Josh Winskill
Josh Winskill

Reputation: 359

How do I make sure I'm returning the correct boolean in a function?

I'm going through Apple's Swift Programming guide, and encountered the following function on page 146:

func containsCharacter(#string: String, #characterToFind: Character) -> BOOL {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

Why is it that the return false snippet present at this point in the function? why wouldn't this function look something like this:

func containsCharacter(#string: String, #characterToFind: Character) -> BOOL {
    for character in string {
        if character == characterToFind {
            return true
        } else {
            return false
        }
    }
}

How is it that the function works the way it is displayed in Apple's book?

Thank you!

Upvotes: 1

Views: 75

Answers (1)

David Heffernan
David Heffernan

Reputation: 613531

I guess the first thing to say, which perhaps you have not yet realised, is that a return statement terminates execution of the function. The value of the return statement is passed to the caller, and execution returns to the caller.

So, with that understood, let's look at this function. It searches in a string for a particular character. It does so by checking against all characters of the string looking to find a match. If it finds a match it returns true. Otherwise it continues to the next character. If the loop completes, then it follows that no matching character was found, and so the function can then return false. It needs to get to the end of the loop before it can be sure that there was no match.

Written your way, the loop is pointless. The function is guaranteed to return from the first iteration. So the loop would never get past the first iteration, and the function would only compare against the first character. And, just for good measure, if the string was empty, the return value would be undefined.

Upvotes: 1

Related Questions