gpt4 book ai didi

arrays - 如何在 Swift 中对具有关联值的枚举数组进行排序?

转载 作者:可可西里 更新时间:2023-11-01 02:00:16 24 4
gpt4 key购买 nike

关于 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 会填充一些 cellTypesecondaryText 的值包含日期,如下所示:

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

对这个数组进行排序的最佳方法是什么?提前致谢!

最佳答案

(我是在手机上写的,所以..如有必要请修正语法)

在排序函数中使用以下代码:

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
}

您的问题是,您正在访问枚举的参数,就好像它是类/结构的实例一样。

关于arrays - 如何在 Swift 中对具有关联值的枚举数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46977285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com