Search code examples
swiftenumsswift4associated-value

How can you do a simple inline test for an enumeration's case that has associated values you don't care about?


Given this code:

class Item{}

func foo(item:Item){}

enum SelectionType{
    case single(resultsHandler:(Item)->Void)
    case multi(resultsHandler:([Item])->Void)
}

var selectionType:SelectionType = .single(resultsHandler:foo)

// This line won't compile
let title = (selectionType == .single)
    ? "Choose an item"
    : "Choose items"

How can you update the part that won't compile?


Solution

  • A ternary operator cannot work for enums with associated values, because the classic equality operator does not work with them. You have to use pattern matching, or if case syntax:

    let title: String
    if case .single = selectionType {
        title = "Choose an item"
    } else {
        title = "Choose items"
    }