Skip to content

Access an associated value

Giuseppe Lanza edited this page Aug 22, 2019 · 2 revisions

Having a CaseAccessible enum

enum MyError: CaseAccessible, Error {
    case notFound(String)
    case noConnection(String)
    case failedWithMessage(String)
}

There are two ways to access an associated value of an enum case

By type

The first is by specifying which is your return type and using the associatedValue() function.

let value: String? = someCase.associatedValue()
// or with subscript
let value = someCase[expecting: String.self] // String?

This will return a string if the associated value of this enum instance is actually a string, regardless of which is the actual case. This is particularly useful for those enums that have cases with associated values having similar meaning, like the MyError example where all associated values represent an error message

By case

The second way to access an enum associated value is to optionally extract it when the instance is matching a specific case, using the associatedValue(matching:) function:

let myError: MyError
let errorMessage = myError.associatedValue(matching: MyError.noConnection) // String?

or by using the case subscript

let errorMessage = myError[case: MyError.noConnection] // String?