关于StackOverflow的第一个问题......请善待。 :)
我有一组带有关联值的枚举,我想按时间顺序排序。其中一个值包含一个日期(作为字符串),该日期将显示并应用于排序。
目前看来是这样的:
enum cellType {
case standard(text: String, icon: UIImage, hasChildren: Bool, reference: String)
case detailed(text: String, secondaryText: String, icon: UIImage, hasChildren: Bool, reference: String)
var identifier: String {
switch self {
case .standard: return "standardCell"
case .detailed: return "detailedCell"
}
}
}
var cellData: [cellType]
然后cellData
会填充一些cellType
个。 secondaryText
的值包含日期,如下所示:
print(cellData)
// [
// AppIdentifier.cellType.detailed(text: "Title A", secondaryText: "2017-10-20T10:04:00.000+02:00", icon: <UIImage: 0x60c0002a6660>, {12, 21}, hasChildren: false, reference: "40693"),
// AppIdentifier.cellType.detailed(text: "Title B", secondaryText: "2016-12-14T10:04:00.000+02:00", icon: <UIImage: 0x60c0002a6660>, {12, 21}, hasChildren: false, reference: "40632")
// AppIdentifier.cellType.detailed(text: "Title C", secondaryText: "2017-10-20T10:07:00.000+02:00", icon: <UIImage: 0x60c0002a6660>, {12, 21}, hasChildren: false, reference: "40694"),
// AppIdentifier.cellType.detailed(text: "Title D", secondaryText: "2017-11-16T10:34:00.000+02:00", icon: <UIImage: 0x60c0002a6660>, {12, 21}, hasChildren: false, reference: "40633"),
// AppIdentifier.cellType.detailed(text: "Title E", secondaryText: "2017-10-19T10:12:00.000+02:00", icon: <UIImage: 0x60c0002a6660>, {12, 21}, hasChildren: false, reference: "40682"),
// ]
当我尝试对数组进行排序时,以下显然过于简单:
var cellDataSorted = cellData.sorted(by: {$0.detailed.secondaryText < $1.detailed.secondaryText})
// Swift Compiler Error: enum element ’detailed’ cannot be referenced as an instance member
对这个数组进行排序的最佳方法是什么?提前谢谢!
答案 0 :(得分:1)
(我在手机上写这个,所以..如果需要的话修复语法)
在排序函数中使用以下代码:
if case .detailed(_, let date0, _, _, _) = $0, case .detailed(_, let date1, _, _, _) = $1 {
return date0 < date1
} else {
// One of them didn't have date (should never happen)
return true
}
您的问题是,您正在访问枚举的参数,就好像它是类/结构的实例一样。