Sunday, 19 January 2025

Pattern Matching in Swift

When it comes to pattern matching, Swift provides us with some great tools to validate and write clean code that is also very easy to understand. Consider below example: 

let name: String? = "Alex"

let age: Int? = 35

For matching optional data, we can use .some match with properties that hold a value (something that is not nil), and .none to match with properties without any data (== nil). Here is how a simple switch statement would look like: 

switch (name, age) {

    case let(.some(matchedName), .some(matchedAge)):

    print("Hello \(matchedName)")

    

    case let(.some(name), .none):

    print("Hello \(name), How old are you?")

    

    default:

    print("Who are you?")

}

Consider another property which is an array data that may contain some nil values:

let data: [Any?] = [1, "Hello", true, nil, "Ted"]

We can use a for loop to iterate and process data elements that have some value using .some keyword:

for case let .some(value) in data {

    print(value)

}


This will ensure we only pick and process non-nill values. 



No comments:

Post a Comment