擴展可以向已有的類、結構體和枚舉添加新的嵌套類型:
extension Character {
enum Kind {
case Vowel, Consonant, Other
}
var kind: Kind {
switch String(self).lowercaseString {
case "a", "e", "i", "o", "u":
return .Vowel
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
return .Consonant
default:
return .Other
}
}
}
該例子向Character添加了新的嵌套枚舉。這個名為Kind的枚舉表示特定字符的類型。具體來說,就是表示一個標準的拉丁腳本中的字符是元音還是輔音(不考慮口語和地方變種),或者是其它類型。
這個類子還向Character添加了一個新的計算實例屬性,即kind,用來返回合適的Kind枚舉成員。
現(xiàn)在,這個嵌套枚舉可以和一個Character值聯(lián)合使用了:
func printLetterKinds(word: String) {
println("'\\(word)' is made up of the following kinds of letters:")
for character in word {
switch character.kind {
case .Vowel:
print("vowel ")
case .Consonant:
print("consonant ")
case .Other:
print("other ")
}
}
print("\n")
}
printLetterKinds("Hello")
// 'Hello' is made up of the following kinds of letters:
// consonant vowel consonant consonant vowel
函數(shù)printLetterKinds的輸入是一個String值并對其字符進行迭代。在每次迭代過程中,考慮當前字符的kind計算屬性,并打印出合適的類別描述。所以printLetterKinds就可以用來打印一個完整單詞中所有字母的類型,正如上述單詞"hello"所展示的。
注意:
由于已知character.kind是Character.Kind型,所以Character.Kind中的所有成員值都可以使用switch語句里的形式簡寫,比如使用.Vowel代替Character.Kind.Vowel