Swift初学者错误

时间:2017-11-19 03:31:13

标签: swift

原始问题是"函数startsWithVowel应该采用单个String参数并返回一个Bool,指示输入字符串是否以元音开头。如果输入字符串以元音开头返回true,否则返回false。"

func lowercase(a: String) ->String{
    return a.lowercaseString
}

func lowercase(a: String) ->String{
    return a.lowercaseString
}
func beginsWithVowel(a: String) ->Bool {
    if  a.characters[a.startIndex] != ("a") && a.characters[a.startIndex] != ("e") && a.characters[a.startIndex] != ("i") && a.characters[a.startIndex] != ("o")  && a.characters[a.startIndex] != ("u")  {
        print("The word must start with a vowel letter.")
        return false
    }else {
        print("Succes!")
        return true
    }
}

当a =""

beginsWithVowel(lowercase(""))

发生错误。

我应该添加什么来使功能说出提示句而不是错误?

我曾尝试将这些添加到我的代码中,但错误仍然存​​在(ps:失败后添加了func小写)

a.characters[a.startIndex] != ("")

if a.characters.count == 0 {

}

1 个答案:

答案 0 :(得分:0)

如果你的字符串为空,你可以简单地返回false,否则用元音创建一个字符串并检查它是否包含字符串的第一个字符:

Swift 3

func beginsWithVowel(a: String) -> Bool {
    return a.isEmpty ? false : "aeiouAEIOU".characters.contains(a.characters.first!)
}

Swift 4

func beginsWithVowel(a: String) ->Bool {
    return a.isEmpty ? false : "aeiouAEIOU".contains(a.first!)
}
beginsWithVowel(a: "Apple") // true

请注意,对于带重音的元音,它将返回false。如果你想让你的方法变音不敏感,你可以使用字符串的方法func folding(options: String.CompareOptions = default, locale: Locale?) -> String来返回没有重音的字符串进行比较:

Swift 3

func beginsWithVowel(a: String) ->Bool {
    return a.isEmpty ? false : "aeiouAEIOU".characters.contains(a.folding(options: .diacriticInsensitive, locale: nil).characters.first!)
}

Swift 4

func beginsWithVowel(a: String) ->Bool {
    return a.isEmpty ? false : "aeiouAEIOU".contains(a.folding(options: .diacriticInsensitive, locale: nil).first!)
}
beginsWithVowel(a: "águia") // true