无法将类型 'String' 的值转换为预期的参数类型 'Bool'

Cannot convert value of type 'String' to expected argument type 'Bool'

我正在尝试编写一个函数,如果字符串 str 以元音开头,该函数将 return 为真。下面的代码可以正常编译

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")

问题是当我将第一个字符与多个字符进行比较时,例如

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

然后我收到错误“无法将类型 'String' 的值转换为预期的参数类型 'Bool'”

我一直在摆弄代码,但到目前为止运气不好,我们将不胜感激。谢谢你。

你应该这样写:

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

您收到错误,因为编译器试图将 "e" 和 "i" 都转换为 Bool 类型。

Swift 无法推断出您要创建的逻辑。 Swift 的逻辑变成这样:

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

等同于if(<Boolean expression> || "e" || "i")

等同于if(<Boolean expression> || <String expression> || String expression)

替代解决方案可以是:

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

而不是使用 if else 开关会更有效率:

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
    }
}

当您执行 "a" || "e" || "i" 时,您是在 strings 之间进行比较。使用此代码:

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

    // Your Code...

}

布尔 OR 运算符 || 需要布尔表达式。

因此您必须编写 EXPR == "a" || EXPR == "e" || EXPR == "i",其中 EXPR 是获取第一个字符的表达式。

但是有一个更简单的解决方案(代码是 Swift 4)

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

它也考虑了空字符串的情况。