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:
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")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.