Confused Confused - 1 month ago 10
Swift Question

Swift switch case to use contents of array, syntax?

The Swift Book from Apple has a switch example that uses vowels as a case.

Question.
Instead of having this list of vowels, is it possible to use an array that contained this contents? if so, what's the syntax for doing this?




~ from Apple Swift Book ~


The following example removes all vowels and spaces from a lowercase
string to create a cryptic puzzle phrase:


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"

Answer

Yes:

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

case matching in Swift relies on the pattern matching operator (~=). If you define a new overload for it, you can shorten the code even more:

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