问题
I need to check if a word starts with a vowel or a consonant, something like that:
let word = "ciao"
if wordStartsWithVowel {
print("Word starts with Vowel!")
}
How can I do that?
回答1:
extension Character {
var isVowel: Bool {
return "aeiouAEIOU".contains {
String($0).compare(String(self).folding(options: .diacriticInsensitive, locale: nil), options: .caseInsensitive) == .orderedSame
}
}
}
extension StringProtocol {
var startsWithVowel: Bool {
return first?.isVowel == true
}
}
let word = "ciao"
print(word.startsWithVowel) // false
let word2 = "é"
print(word2.startsWithVowel) // true
回答2:
let vowels: [Character] = ["a","e","i","o","u"]
let word = "ciao"
if vowels.contains(word.lowercased().characters.first!) {
print("Word starts with Vowel!")
}
.lowercaseString is important because, otherwise, uppercase vowels wouldn't be recognised as vowels.
来源:https://stackoverflow.com/questions/35493089/check-if-a-word-starts-with-a-vowel-or-a-consonant