按其他数组中的值顺序对数组进行排序 [英] Sort array by order of values in other array
本文介绍了按其他数组中的值顺序对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个定义订单的数组
I have one array that defines an order,
let orderSettingArray = ["Admiral", "Captain", "Lieutenant"]
和另一个包含其中一些值的数组
and another array with a few of these values
var myArray = ["Lieutenant", "Captain"]
我想对myArray
进行排序以反映orderSettingArray
的顺序:
I want to sort myArray
to reflect the order of orderSettingArray
:
var myArraySorted = myArray.getSorted(by: orderSettingArray)
现在print(myArraySorted)
应该打印["Captain", "Lieutenant"]
推荐答案
更新
我为此找到了一个更好的设计.它有很多改进:
Update
I've found a better design for this. It has quite a few improvements:
- 我使用
Dictionary
加快了订单查询的速度 - 通过将此行为提取为单独的类型,可以对字典进行缓存并在多种排序之间重用
- 排序推导与排序是分离的,因此可以以更多方式使用
-
omitEntirely
责任已完全删除.相反,应该通过简单调用hardcodedOrdering.contains
作为谓词来完成filter
.
- I use a
Dictionary
to speed up ordering look-ups - By extracting this behaviour into a separate type, the dictionary can be cached and reused between multiple sorts
- The ordering-derivation is decoupled from sorting, so it could be used in more ways
- The
omitEntirely
responsibility was removed entirely. It should instead by done by a simple call tofilter
, withhardcodedOrdering.contains
as the predicate.
这篇关于按其他数组中的值顺序对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文