Associated Values in Swift: What It Is, Syntax, and Examples

Author: IT Sectr Published: 2026-06-17 Reading time: 6 min

Associated Values — a Swift mechanism that allows attaching arbitrary data to each enum case individually. Unlike raw values, where all cases have the same type of values, associated values can differ in type and quantity for each case. According to Apple Documentation, 2026, this is a key capability for accurately modeling a domain without creating additional wrapper types.

Key Takeaways

  • Associated Values — individual data attached to an enum case
  • Types of associated values can differ for each case
  • Extraction is done via value binding in switch or if case
  • Mutual Exclusion — associated values are incompatible with raw values
  • Practice — modeling errors, query results, and UI states

What Are Associated Values?

Associated Values are additional information that an enum case can store along with itself. Unlike raw values, which are fixed at the declaration level, associated values are set when creating an enum instance.

Imagine modeling a payment method: the creditCard case can store the last 4 digits and expiration date, while the applePay case stores nothing. With associated values, this is implemented naturally, without subclasses or optional fields.

According to Apple documentation, associated values turn an enum from a simple set of constants into an algebraic data type (sum type), characteristic of functional languages. This significantly enhances code expressiveness.

Associated Values Syntax

Associated Values are declared in parentheses after the case, specifying parameter names and types, similar to functions.

swift
enum MediaFile {
    case image(width: Int, height: Int, format: String)
    case video(duration: Double, codec: String)
    case audio(bitrate: Int)
    case unknown
}

When creating an instance, associated values are passed as arguments:

swift
let photo = MediaFile.image(width: 1920, height: 1080, format: "jpeg")
let clip = MediaFile.video(duration: 120.5, codec: "h264")

Swift does not impose restrictions on the number or types of associated values. You can use generics, closure functions, and other enums inside associated values. This makes it possible to build complex nested structures.

Parameter names of associated values are used as argument labels when creating an instance — this improves code readability. When extracted via switch, the names serve as documentation, clarifying the meaning of each value. This approach makes the code self-documenting and reduces the likelihood of errors when matching data. This is especially valuable in team development of large iOS applications.

Switch with Associated Values

Switch is the primary way to extract associated values. Values are bound to constants or variables via let or var.

swift
func describe(_ file: MediaFile) -> String {
    switch file {
    case .image(let w, let h, let fmt):
        return "Image \(w)x\(h) .\(fmt)"
    case .video(let duration, let codec):
        return "Video \(duration)s, \(codec)"
    case .audio(let bitrate):
        return "Audio \(bitrate)kbps"
    case .unknown:
        return "Unknown format"
    }
}

Swift supports partial matching — you can specify concrete values for associated values:

swift
switch file {
case .image(let w, let h, "png"):
    print("PNG image \(w)x\(h)")
case .image(1920, 1080, _):
    print("Full HD image")
default:
    break
}

Using a wildcard (_) allows ignoring unnecessary associated values, and constants in cases let you check for matches with specific values.

Associated Values vs Raw Values

Many beginner developers confuse associated values with raw values. These are different mechanisms with different use cases.

CharacteristicRaw ValuesAssociated Values
Data TypeOne type for all casesDifferent types for each case
Assignment TimeAt enum declarationAt instance creation
MandatoryAll cases have a valueSome cases may have no values
CompatibilityMutually exclusive — cannot be used simultaneously

According to Swift Evolution, associated values were introduced in Swift 2.0 as part of the enum redesign. They provide an algebraic approach to types, where each case is a separate constructor with its own signature.

Practical Examples of Associated Values

Associated Values are actively used in real iOS projects. Let's consider three typical scenarios.

Modeling API Responses

swift
enum APIResponse<T: Codable> {
    case success(data: T, cached: Bool)
    case failure(error: Error, retryAvailable: Bool)
    case loading(progress: Double)
}

UI State Machine

swift
enum ViewState<T> {
    case idle
    case loading(message: String)
    case loaded(data: T)
    case error(message: String, retryAction: () -> Void)
}

With associated values, enum becomes a powerful tool for state machines: each case is a state, associated values are parameters of that state. The compiler guarantees that all transitions are handled.

Extraction via if case and guard case

To check a single case without switch, use if case or guard case. This is more compact when you need to handle only one option.

swift
let error = NetworkError.timeout(seconds: 30)

if case .timeout(let seconds) = error {
    print("Request timed out after \(seconds)s")
}

guard case .httpError(let code, _) = error else {
    return
}
print("HTTP error with code \(code)")

Frequently Asked Questions

Can an enum have associated values without parameters?

Yes, a case can have no associated values — for example, case unknown. Such cases behave like regular enum cases without additional data. This is convenient for marker states.

How to compare two enums with associated values?

Swift does not generate Equatable automatically for enums with associated values (before Swift 4.2+). Add an explicit Equatable implementation or use switch to compare each case sequentially.

Can associated values be used in recursive enums?

Yes, associated values in indirect enums are a standard technique for building trees and linked lists. A case can contain an associated value of the same type marked with indirect.

How do associated values differ from optional properties in a struct?

Associated Values are type-safe — each case is guaranteed to have only its own data. In a struct with optionals, every instance contains all fields, and runtime nil checks are needed.

Do associated values support Codable?

Swift does not generate Codable automatically for enums with associated values. A manual implementation of encode and decode is required via switch over cases using custom coding keys.

Summary

  • Associated Values — a mechanism for attaching different data to each enum case
  • Syntax — declaring parameters in parentheses after the case, like functions
  • Extraction via switch with let binding or if case
  • Incompatible with raw values — use only one
  • Generics in associated values make enum a universal container
  • State Machine — a typical use case for associated values in iOS

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also