swiftenumsassociated-object

How can you extract associated values from a specific instance of an enum's case?


Consider this enum...

enum SelectionMode {
    case none     (position:TextPosition)
    case normal   (startPosition:TextPosition, endPosition:TextPosition)
    case lines    (startLineIndex:Int, endLineIndex:Int)
}

If it's passed into a function, you can use a switch statement with each case receiving the associated values, like so...

let selectionMode:SelectionMode = .lines(4, 6)

switch sectionMode {
    case let .none   (position): break;
    case let .normal (startPosition, endPosition): break;
    case let .lines  (startLineIndex, endLineIndex):
        // Do something with the indexes here

}

What I'm wondering is if I know for instance I'm being handed a '.lines' version, how can I get the associated values without having to use a switch statement?

i.e. can I do something like this?

let selectionMode:SelectionMode = .lines(4, 6)

let startLineIndex = selectionMode.startLineIndex

So is something similar to this possible?


Solution

  • A simple assignment without any runtime check won't work because the compiler cannot know which value the selectionMode variable contains. If your program logic guarantees that it is .lines then you can extract the associated value with pattern matching:

    guard case .lines(let startLineIndex, _) = selectionMode else {
        fatalError("Expected a .lines value")
        // Or whatever is appropriate ...
    }