Swift if case pattern matching

We are all familiar with the error “Switch must be exhaustive“. Adding a default or adding all cases can resolve this error condition but what if we want to compare only one enum case?.

If case is here for the rescue

If we do not wish to be exhaustive with all cases of a enum and still need to compare a specific case out of it the we can use if-case. Give below are few code example try in playground

// Paste this code in playground
import UIKit
enum Animal {
    case cat(age:Int)
    case dog
}

let gato = Animal.cat(age: 1)
let bhowao = Animal.dog

When we need to use the associated value in a case then we require If-case let

// let when you have to use associated value
if case let Animal.cat(age) = gato, age < 2{
    print("kitten")
}

A simple if-case will be enough for a compare when we do not need to use associated value

// no need of let if are not going to use associated value
if case .cat(age:1) = gato {
    print("same age cat")
}

if case .dog = bhowao {
    print("its a dog")
}

guard can also be used with case

//using guard
func guardTest() {
    guard case let .cat(age) = gato else {
        print("Not same age cat")
        return
    }
    print("Age of cat is \(age)")
}
guardTest()

Hope this helps !!!

A pat on the back !!