What are patterns in Swift?

In Swift, patterns are a mechanism used to match and decompose values. For instance, the pattern (a, b) matches with the tuple (5, 6). We can extract parts and assign each part to a constant or variable name. For example, if we want to assign the first element of the tuple (5, 6) to the constant 'a' and the second element to the constant 'b', we can use the pattern (a, b) = (5, 6).

Note: Pattern represents the structure of the value instead of the value itself.

Let's implement the tuple example in the following section.

Example

We can use a pattern to extract the values from a tuple into individual variables or to match an optional value and unwrap it into a variable if it contains a value.

Here's an example of using a pattern to match the values of a tuple:

let myTuple = (1, "hello", true)
let (num, str, bool) = myTuple
print(num) // Output: 1
print(str) // Output: "hello"
print(bool) // Output: true

In the code above, we define a tuple with three values, and then use a pattern to match the values of the tuple into three separate variables (num, str, and bool). These variables are then printed to the console.

Example

We can also use patterns to match the values of an enumeration and execute specific code for each case. Here's an example:

enum MyEnum {
case caseOne(String)
case caseTwo(Int)
}
let myValue = MyEnum.caseOne("hello")
switch myValue {
case .caseOne(let str):
print("String value is: \(str)") // Output: "String value is: hello"
case .caseTwo(let num):
print("Number value is: \(num)")
}

In the code above, we define an enumeration with two cases (caseOne and caseTwo). We then use a pattern in a switch statement to match the value of myValue with the caseOne case, and extract the value of the associated string using a value binding pattern (let str). If myValue is caseTwo, the code associated with that case will be executed.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved