Component - Enums with associated values
This UI component demonstrates how Swift enums can hold extra information with each case using associated values. It shows a simple screen with a message that changes based on the enum value selected.
This UI component demonstrates how Swift enums can hold extra information with each case using associated values. It shows a simple screen with a message that changes based on the enum value selected.
View
└── VStack
├── Text
└── Buttonenum with associated values in Swift?case name(String) uses parentheses correctly.enum Result {
case success(String)
case failure(Int)
}
let result = Result.success("Done")
switch result {
case .success(let message):
print(message)
case .failure(let code):
print("Error \(code)")
}result is .success("Done")..success(let message) and prints the message "Done".enum Direction {
case up(Int)
case down(Int)
}
let dir = Direction.up(10)
switch dir {
case .up:
print("Going up")
case .down:
print("Going down")
}up and down have Int associated values..up and .down do not extract the Int value with let, causing a compile error.success carrying a String message, failure carrying an Int error code, and loading with no data. Which is the correct enum definition?success needs a String, failure an Int, loading no data.Pass the test and this pattern moves unknown