Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 983
Confused Avatar asked Oct 14 '16 03:10

Confused


People also ask

Can we use array in switch case?

Yes, you can pass an array to a switch.

How do you make a switch case in Swift?

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.

What is array and write syntax in Swift?

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.

Can we use where in switch case in Swift?

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.


1 Answers

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)
    }
}
like image 180
Code Different Avatar answered Oct 07 '22 08:10

Code Different