How to Access an Enum Associated Value in Swift

There are multiple ways to access an enum associated value in Swift. One of the most common methods is using a switch statement:

enum MediaType {
    case image(URL)
    case video(URL)
    case empty
}

switch media {
case .image(let url):
    // Handle image URL
case .video(let url):
    // Handle video URL
case .empty:
    break
}

This can get cumbersome, particularly when you just need to grab a single value without needing to check over all of the possible cases and do something with each. A way to avoid using a switch statement is with an if case let or guard case let statement.

if case let .video(url) = media {
    // Do something with url
}

Or you can use this slight variation:

if case .video(let url) = media {
    // Do something with url
}

To get the value with a guard statement, use:

guard case let .video(url) = media else { return }
    // Do something with url

or

guard case .video(let url) = media else { return }
    // Do something with url