Swift – Cannot convert value of type ‘String’ to expected argument type ‘Bool’

boolean-expressionswift

I am trying to write a function that will return true if the String str starts with a vowel. the following code will compile fine

func beginsWithVowel(str: String) -> Bool {
    if(str.characters.count == 0){
        return false
    } else if(str.characters[str.startIndex] == "a"){
        return true
    }
    return false
}
beginsWithVowel(str: "apple")

the problem is when I compare the first character to more than one character, for example

else if(str.characters[str.startIndex] == "a" || "e" || "i")

then I get the error 'Cannot convert the value of type 'String' to expected argument type 'Bool''

I've been fiddling with the code but no luck so far, any help would be appreciated. Thank you.

Best Answer

Swift cannot infer the logic you are trying to make. The logic to Swift becomes something like this:

if(str.characters[str.startIndex] == "a" || "e" || "i")

is equivalent to if(<Boolean expression> || "e" || "i")

is equivalent to if(<Boolean expression> || <String expression> || String expression)

An alternative solution can be:

if(["a", "b", "c"].contains(str.characters[str.startIndex])){

Related Topic