enum Associated Values
Swift enums can have associated values of different types for each case. This lets a single enum model multiple patterns of data.
Syntax
// Defining an enum with associated values
enum EnumName {
case case1(Type1)
case case2(Type2, Type3)
case case3(label: Type4)
}
// Extracting associated values (switch)
switch value {
case .case1(let x):
// Use x
case .case2(let a, let b):
// Use a and b
}
Syntax reference
| Syntax | Description |
|---|---|
| case name(Type) | Defines a case with one associated value. |
| case name(Type1, Type2) | Defines a case with multiple associated values. |
| case name(label: Type) | Defines an associated value with a label. |
| Pattern matching with switch | Use case .caseName(let x): to extract associated values. |
| if case let pattern = value | Branches on a specific case only. |
Sample code
// Modeling an HTTP response
enum HTTPResult {
case success(statusCode: Int, data: String)
case failure(statusCode: Int, message: String)
case loading
}
// Usage examples
let result = HTTPResult.success(statusCode: 200, data: "{ \"name\": \"Swift\" }")
let error = HTTPResult.failure(statusCode: 404, message: "Not Found")
// Pattern matching with switch
func handleResult(_ result: HTTPResult) {
switch result {
case .success(let code, let data):
print("Success (\(code)): \(data)")
case .failure(let code, let message):
print("Failure (\(code)): \(message)")
case .loading:
print("Loading...")
}
}
handleResult(result)
handleResult(error)
// if case let: handle only a specific case
if case .success(let code, _) = result, code == 200 {
print("200 OK!")
}
// Recursive enum (indirect)
indirect enum Tree {
case leaf(Int)
case node(Tree, Tree)
}
let tree = Tree.node(.leaf(1), .node(.leaf(2), .leaf(3)))
Notes
Enums with associated values are well-suited for modeling results that carry different data on success or failure (like the Result type), or for representing network states. Each case can hold values of a different type and count.
Recursive enums (such as tree structures) require the indirect keyword, which tells the compiler to use an indirect reference for storage. Associated values and raw values cannot be used together — you can only use one or the other.
For adding methods to an enum, see enum methods, properties, and mutating.
If you find any errors or copyright issues, please contact us.