Pattern Matching with case let statements in Swift

Tram Ho

Pattern Matching is a check to see if a string or data structure contains a certain element. In Swift, Pattern Matching is done via case let statements with different types of data structures.

Enums

Pattern Matching is extremely effective when used with enums:

When using the switch statement for enums with associated values, the case let statement can be used to test a case and assign a value to a variable. Moreover, you can filter the attached value through the where statement.

Optionals

The nature of Optional in Swift is that enum has two cases, so using case let for optional is the same as for enum.

In the case of .some(value) , could it be written as a value? .

Tuples

Pattern Matching can also be used effectively on tuple data structures.

Conditional statements

case let can also be used in conjunction with conditional statements:

, or:

Iterative statement

In addition to use in branching structures, case let can be used in loops as well:

References

https://swiftwithmajid.com/2019/02/06/pattern-matching-with-case-let/

Share the news now

Source : Viblo