| Start | ||||
|---|---|---|---|---|
| Switch and Optionals Some example cases when the result is an optional. |
||||
Basic Use switch statements also work with data types other than integers. They work with any data type.Here's an example of switching on a string: This will print the following: |
||||
| Matching a Range A single case in a switch statement can match a range of values. |
||||
| Using the where statement in a switch The where statement may be used within a switch case match to add additional criteria required for a positive match. The following example checks not only for the range, but also if the number is odd or even: |
||||
| Partial matching Switch statement make use of partial matching.
Note: using the underscore to mean that you don't care about the value. If you don't want to ignore the value, then you can use it in your switch statement, like this: Here, the axis cases use the let syntax to pull out the pertinent values. The code then prints the values using string interpolation to build the string. Note: you don't need a default in this switch statement. This is because the final case is essentially the default—it matches anything, because there are no constraints on any part of the tuple. If the switch statement exhausts all possible values with its cases, then no default is necessary. We can also use the let-where syntax to match more complex cases. For example: Here, We match the "y equals x" and "y equals x squared" lines. |
||||
| Matching Multiple Values A single case in a switch statement can match on multiple values. |
||||
| Satisfy one of multiple constraints using switch You can create a tuple and use a switch like so: |
||||
| Switch and Enums The Switch statement works very well with Enum values Since we provided a case for each possible value of car, we omit the |
||||
| Switches and tuples Switches can switch on tuples: |
||||
| Matching based on class - great for prepareForSegue You can also make a switch statement switch based on the class of the thing you're switching on. An example where this is useful is in Swift switch statements to the rescue. Use Swift In Swift 3 the sytax has changed slightly: |
||||
| Switch fallthroughs It is worth noting that in swift, unlike other languages people are familiar with, there is an implicit break at the end of each case statement. In order to follow through to the next case (i.e. have multiple cases execute) you need to use this is useful for things like streams. Parameters
RemarksSupply a case for every possible value of your input. Use a By default Switches in Swift will not continue to check other cases after a case has been matched. |
Read Article
https://develop.horje.com/learn/1434/reference