Swift Tuples & Type Aliases

Swift Tuples and Type Aliases

As you advance in Swift, you'll discover features designed to make code simpler and more expressive.

Two such features are Tuples and Type Aliases.

Tuples allow you to group multiple values together, while Type Aliases let you provide alternative names for existing data types.


What are Tuples?

A tuple groups multiple values into a single compound value.

The values within a tuple can be of any type, and they don't have to be of the same type as each other.

Creating a Tuple:

// A tuple holding an Int and a String
let httpError = (404, "Not Found")

// You can access elements by their index (starting at 0) print("Error Code: \(httpError.0)") print("Error Message: \(httpError.1)")


Naming Tuple Elements

Relying on numbers like .0 and .1 can make your code hard to read.

Fortunately, Swift allows you to name the individual elements inside a tuple when it is defined.

Named Tuples:

let userStatus = (statusCode: 200, description: "OK")

print("Status: \(userStatus.statusCode)") print("Message: \(userStatus.description)")


Returning Multiple Values

The most common use case for tuples is returning multiple values from a function.

Instead of creating complex objects or arrays, a function can quickly return a tuple containing several pieces of related data.

Tuples in Functions:

func getMinMax(numbers: [Int]) -> (min: Int, max: Int) {
    // For simplicity, hardcoding the logic
    return (min: 1, max: 100)
}

let bounds = getMinMax(numbers: [1, 5, 100, 2]) print("Minimum is \(bounds.min) and Maximum is \(bounds.max)")


What is a Type Alias?

A Type Alias defines an alternative name for an existing data type.

You define type aliases with the typealias keyword.

They are extremely useful when you want to refer to an existing type by a name that makes more contextual sense in your app.

Using Type Aliases:

typealias AudioSample = UInt16

// Now AudioSample acts exactly like UInt16 var maxAmplitudeFound = AudioSample.min

print(maxAmplitudeFound)


Exercise

Which keyword is used to provide an alternative name for an existing data type in Swift?