Confused
Confused

Reputation: 6278

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"

Upvotes: 9

Views: 7433

Answers (1)

Code Different
Code Different

Reputation: 93151

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

Upvotes: 20

Related Questions