Swift按枚举宣布的命令排序一系列枚举
我如何对声明的顺序排序我的枚举数组?
enum EducationOptions: String {
case gcse = "GCSE"
case aLevel = "A Level"
case bachelors = "Bachelors"
case masters = "Masters"
case doctorate = "Doctorate"
case other = "Other"
}
var arrayOfEducationOptions: [EducationOptions] = [.masters, .gcse, .aLevel]
我想按枚举中声明的顺序排序阵列deducationoptions以获取[.gcse,.alevel,.masters]
How can I sort my array of enums to be sorted by the declared order?
enum EducationOptions: String {
case gcse = "GCSE"
case aLevel = "A Level"
case bachelors = "Bachelors"
case masters = "Masters"
case doctorate = "Doctorate"
case other = "Other"
}
var arrayOfEducationOptions: [EducationOptions] = [.masters, .gcse, .aLevel]
I want to sort arrayOfEducationOptions to get [.gcse, .aLevel, .masters] as per the order declared in the enum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Vadim似乎有正确的想法,但是如果您想对教育的任意列表进行分类,则可以使用这样的代码:
请注意,该代码是一个天真的实现,并且随着案例数量的增长而扩展很差。 (它至少具有
o(n²)
时间性能,甚至可能更糟(o(n²•log n)
)。对于要重写的较大枚举它创建一个结构数组,其中包括来自枚举样本阵列的索引,然后对进行排序。It seems like Vadim has the right idea, but if you want to sort an arbitrary list of EducationOptions, you could use code like this:
Note that that code is a naive implementation, and would scale very poorly as the number of cases grows. (It would have at least
O(n²)
time performance, and probably even worse (O(n²•log n)
). For larger enums you'd want to rewrite it to create an array of structs that included indexes from the sample array of enums, and then sort that.使其符合
caseIterable
协议,并使用静态allccases
属性:Make it conform to
CaseIterable
protocol and use the staticallCases
property:在枚举中添加可比的协议?
然后,您可以对数组进行排序。
在具有字符串原始值时,可能有更好的方法来设置数组中的订单值,但不是我的头顶
Add a comparable protocol to the enum?
then you can just sort the array.
there may be a better way to set the order values in the array while having the String raw value as well, but not of the top of my head