3

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.

TT--
  • 2,956
  • 1
  • 27
  • 46
Anthony Rubin
  • 69
  • 1
  • 1
  • 14

5 Answers5

4

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])){

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Tushar
  • 3,022
  • 2
  • 26
  • 26
2

You should write it like this:

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

You get the error, because the compiler tries to convert both "e" and "i" to type Bool.

2

Instead of using if else switch will be more efficient:

func beginsWithVowel(str: String) -> Bool {

    guard str.characters.count > 0 else {
        return false
    }

    switch str.characters[str.startIndex]{
        case "a","e","i","o","u": 
        return true

        default:
        return false
    }
}
Hamza Ansari
  • 3,009
  • 1
  • 23
  • 25
1

When you perform "a" || "e" || "i" you are comparing between the strings. Use this code:

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

    // Your Code...

}
Haroldo Gondim
  • 7,725
  • 9
  • 43
  • 62
1

The boolean OR operator || expects boolean expressions.

So you would have to write EXPR == "a" || EXPR == "e" || EXPR == "i" where EXPR is the expression to get the first character.

However there is an easier solution (code is Swift 4)

func beginsWithVowel(str: String) -> Bool {
    return "aeiou".contains(String(str.prefix(1)))
}

It considers also the empty string case.

vadian
  • 274,689
  • 30
  • 353
  • 361