Enums with associated values let you store extra information with each option. This helps keep related data together in a simple way.
0
0
Enums with associated values in iOS Swift
Introduction
When you want to group related options that each hold different extra data.
When you need to handle different types of information in one place, like a message that can be text or an image.
When you want to write clear code that matches on cases and uses their extra data easily.
Syntax
iOS Swift
enum Example {
case optionName(AssociatedType)
}Each case can have one or more associated values inside parentheses.
Associated values can be any type, like String, Int, or even custom types.
Examples
This enum has two cases: one with four Int values, and one with a String.
iOS Swift
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}Here, success holds a message string, failure holds an error object.
iOS Swift
enum Result {
case success(String)
case failure(Error)
}Sample App
This example defines a Media enum with two cases holding different data. The describe function uses a switch to read the associated values and return a description string.
iOS Swift
enum Media {
case photo(name: String, sizeMB: Double)
case video(name: String, durationSec: Int)
}
func describe(media: Media) -> String {
switch media {
case .photo(let name, let sizeMB):
return "Photo named \"\(name)\" with size \(sizeMB)MB"
case .video(let name, let durationSec):
return "Video named \"\(name)\" lasting \(durationSec) seconds"
}
}
let myPhoto = Media.photo(name: "Beach", sizeMB: 3.5)
let myVideo = Media.video(name: "Birthday", durationSec: 120)
print(describe(media: myPhoto))
print(describe(media: myVideo))OutputSuccess
Important Notes
You can use named parameters in associated values for clarity.
Switch statements must cover all enum cases, so you handle every possibility.
Associated values let you keep related data together without extra classes or structs.
Summary
Enums with associated values store extra data with each case.
Use switch to access and use the associated values.
This helps organize related options and their data cleanly.