Swift switch case 使用数组内容语法?

方案1

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

方案2

Swift 中的 

case 匹配依赖于模式匹配运算符 (~=)。如果为它定义一个新的重载,则可以进一步缩短代码:

func ~=(pattern: [T], value: T) -> Bool {
    return pattern.contains(value)
}

for character in puzzleInput.characters {
    switch character {
    case vowels:
        continue
    default:
        puzzleOutput.append(character)
    }
}

你可能感兴趣的:(swift,开发语言,ios)