鉴于此代码:
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"
如何更新无法编译的部分?
答案 0 :(得分:0)
三元运算符不能用于具有关联值的枚举,因为经典的等式运算符不能与它们一起使用。您必须使用模式匹配或if case
语法:
let title: String
if case .single = selectionType {
title = "Choose an item"
} else {
title = "Choose items"
}
答案 1 :(得分:0)
我不知道是否有直接的方式来解决您的需求。
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 .single(_) = selectionType {
print("Choose an item")
}
else {
print("Choose items")
}