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"
Yes, you can pass an array to a switch.
In the most basic form of a switch/case you tell Swift what variable you want to check, then provide a list of possible cases for that variable. Swift will find the first case that matches your variable, then run its block of code. When that block finishes, Swift exits the whole switch/case block.
Swift is a type inference language that is, it can automatically identify the data type of an array based on its values. Hence, we can create arrays without specifying the data type. For example, var numbers = [2, 4, 6, 8] print("Array: \(numbers)") // [2, 4, 6, 8] Create an Empty Array.
Switch Statement: where Clause - Learn Swift | Codecademy. Another neat feature available for the cases of a switch statement is the where clause. The where clause allows for additional pattern matching for a given expression. It can also be used with loops and other conditionals such as if statements.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With