Apple的Swift Book有一个使用元音作为案例的开关示例。
问题。 而不是有这个元音列表,是否可以使用包含此内容的数组?如果是这样,这样做的语法是什么?
来自Apple Swift Book的〜
以下示例从小写中删除所有元音和空格 字符串来创建一个神秘的拼图短语:
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput.append(character)
}
}
print(puzzleOutput)
// Prints "grtmndsthnklk"
答案 0 :(得分:8)
是:
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let vowels: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput.characters {
switch character {
case _ where vowels.contains(character):
continue
default:
puzzleOutput.append(character)
}
}
Swift中的 case
匹配依赖于模式匹配运算符(~=
)。如果为它定义了新的重载,则可以进一步缩短代码:
func ~=<T: Equatable>(pattern: [T], value: T) -> Bool {
return pattern.contains(value)
}
for character in puzzleInput.characters {
switch character {
case vowels:
continue
default:
puzzleOutput.append(character)
}
}