Fork me on GitHub

How Do I Write If Case Let in Swift?

if case let is an abbreviated form of switch

case let immediately precedes the candidate pattern in both versions. However, when using if case let the value comes after the = operator:

if case let Puppy.mastiff(droolRating, weight) = fido {
... // tell fido he's a good boy

is equivalent to:

switch fido {
case let Puppy.mastiff(droolRating, weight):
... // tell fido he's a good boy

let binds associated values

case let is a shortcut so all subsequent associated values can be bound just by providing variable names. Alternatively write let as usual, before each name:

if case Puppy.mastiff(let droolRating, let weight) = fido {
... // does that pup need an extra treat?

Bind a tuple with all the values at once:

if case let Puppy.mastiff(characteristics) = fido {
... // how cute is this doggie, exactly?

Remember the syntactic sugar to match non-nil optionals:

if case let Puppy.mastiff(droolFactor, weight)? = potentialPup {
... // oh thank goodness, a puppy

Omit let entirely if you don't need the associated values:

if case Puppy.mastiff = fido {
... // just hand me the pupster

Add conditions to if and guard using commas

if case let Puppy.mastiff(droolRating, _) = fido, droolRating > 8 {
... // you're going to need a new couch
guard case let Puppy.mastiff(droolRating, _) = fido, droolRating < 10 else {
... // that dog is not coming in the house

Iterate using for, where and logical operators

for case let Puppy.mastiff(droolRating, weight) in rescuePups where droolRating > 5 && weight > 15.0 {
... // I'll take the chubby, soggy ones please

Bind non-optional derived values in chained expressions

if let rescueCenter = nearest(), case let puppies = rescueCenter.puppies, puppies.count < 10 {
... // better hurry or might not get enough

Other more in-depth articles:

  • Swift Pattern Matching In Detail - Benedikt Terhechte
  • Pattern Matching In Swift - Ole Begemann
  • Pattern Matching - Crunchy Development
  • Pro Pattern-Matching in Swift - Nick Teissler, Big Nerd Ranch
  • Using the power of switching with associated values to write elegant, logical, meaningful code -