| title | pattern matching with case let in Swift | |||
|---|---|---|---|---|
| date | 2019-02-08 | |||
| captured | 2019-02-08 16:24:25 UTC | |||
| tags |
|
|||
| source | GitHub issue #409 + https://swiftwithmajid.com/2019/02/06/pattern-matching-with-case-let/ | |||
| aliases | ||||
| status | refined |
Swift's case let keyword enables powerful pattern matching across enums, optionals, and tuples. This provides elegant, readable syntax for destructuring and filtering complex data types.
Source: Pattern Matching with case let
Extract associated values from enum cases with optional filtering:
case let .loaded(shows) // extract value
case let .loaded(shows) where shows.isEmpty // extract + conditionSince optionals are enums (Optional<T>), pattern matching applies directly:
case let value? // matches non-nil (equivalent to .some(value))
case .none // handles nilPattern matching works with tuple grouping:
case ("admin", "admin") // match specific values
case let (_, password) where password.count < 6 // wildcard + conditioncase let integrates with multiple Swift constructs:
if case let- conditional checks with extractionguard case let- early returns when pattern does not matchfor case let- loop filtering:for case let .loaded(shows) in collection where condition
Pattern matching with case let reduces boilerplate while improving code clarity. It replaces verbose switch statements and nested if let chains with concise, expressive syntax that works consistently across enums, optionals, and tuples.
- [[swifty-code]] - broader principles for idiomatic Swift