Swift Enumerations: Using Associated Values for Enhanced Data Modeling

A portrait painting style image of a pirate holding an iPhone.

by The Captain

May 22, 2024

Swift Enumerations with Associated Values

Enumerations, or enums, in Swift are a powerful feature that allows you to define a common type for a group of related values. Enumerations can also have associated values, which enable you to associate additional data with each case of the enum. This can be useful when you need to store different types of data for each case.

Let's say you want to create an enum to represent different types of contacts in an address book. You can define an enum called Contact with cases for different types of contacts, such as email, phone, and address, each with associated values:

enum Contact {
    case email(address: String)
    case phone(number: Int)
    case address(street: String, city: String, zipcode: String)

In this example, the Contact enum has three cases with associated values. For the email case, we associate a string representing the email address. For the phone case, we associate an integer representing the phone number. And for the address case, we associate three strings representing the street, city, and zipcode.

You can create instances of the Contact enum with associated values like this:

let emailContact = Contact.email(address: "john.doe@example.com")
let phoneContact = Contact.phone(number: 1234567890)
let addressContact = Contact.address(street: "123 Main St", city: "Anytown", zipcode: "12345")}

Later, you can switch on the enum and extract the associated values based on the case:

switch emailContact {
case .email(let address):
    print("Email address: \(address)")
case .phone(let number):
    print("Phone number: \(number)")
case .address(let street, let city, let zipcode):
    print("Address: \(street), \(city), \(zipcode)")

Using enums with associated values in Swift can help you model complex data structures in a type-safe and efficient way. Try incorporating enums with associated values into your Swift projects to take advantage of this powerful feature!