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 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 are declared in parentheses after the case, specifying parameter names and types, similar to functions.
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:
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 is the primary way to extract associated values. Values are bound to constants or variables via let or var.
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:
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.
Many beginner developers confuse associated values with raw values. These are different mechanisms with different use cases.
| Characteristic | Raw Values | Associated Values |
|---|---|---|
| Data Type | One type for all cases | Different types for each case |
| Assignment Time | At enum declaration | At instance creation |
| Mandatory | All cases have a value | Some cases may have no values |
| Compatibility | Mutually 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.
Associated Values are actively used in real iOS projects. Let's consider three typical scenarios.
enum APIResponse<T: Codable> {
case success(data: T, cached: Bool)
case failure(error: Error, retryAvailable: Bool)
case loading(progress: Double)
}
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.
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.
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
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.
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.
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.
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.
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
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.
Read also