[英]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? 您如何更新不会编译的部分?
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: 您必须使用模式匹配,或者
if case
语法:
let title: String
if case .single = selectionType {
title = "Choose an item"
} else {
title = "Choose items"
}
I don't know if there is a direct way to address what you are looking for. 我不知道是否有直接的方法可以解决您的需求。
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.