1

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?

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286

2 Answers2

0

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"
}
tktsubota
  • 9,371
  • 3
  • 32
  • 40
  • Ugh! That's what I was afraid of. Leaving it open a little longer for other ways to solve this. I'm thinking maybe an extension or similar. Lots to try. If nothing comes up that's a viable alternative, I'll mark yours as the accepted answer. – Mark A. Donohoe Apr 18 '18 at 16:16
  • 1
    The wildcard pattern is not needed: `if case let .single = selectionType` – Martin R Apr 18 '18 at 16:27
0

I don't know if there is a direct way to address what you are looking for.

My understanding:

  • Enums are not equatable by default, you have to implement Equatable
  • For enums with associated values, even if you implemented it, I don't think it is possible to achieve what you had asked.

Computed variable (Workaround 1):

enum SelectionType{

    case single(resultsHandler:(Item)->Void)
    case multi(resultsHandler:([Item])->Void)

    var title : String {

        let text : String

        switch self {

        case .single(_):
            text = "Choose an item"
        case .multi(_):
            text = "Choose items"
        }

        return text
    }
}

var title = selectionType.title

Use if case (Workaround 2):

if case .single(_) = selectionType {
    print("Choose an item")
}
else {
    print("Choose items")
}
user1046037
  • 16,755
  • 12
  • 92
  • 138