1

鉴于此代码:

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"

如何更新无法编译的部分?

4

2 回答 2

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"
}
于 2018-04-18T16:05:51.717 回答
0

我不知道是否有直接的方法来解决您正在寻找的内容。

我的理解:

  • 枚举默认情况下是不相等的,你必须实现 Equatable
  • 对于具有关联值的枚举,即使您实现了它,我认为也无法实现您所要求的。

计算变量(解决方法 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

使用 if case(解决方法 2):

if case .single(_) = selectionType {
    print("Choose an item")
}
else {
    print("Choose items")
}
于 2018-04-18T16:18:37.043 回答