按其他数组中的值顺序对数组进行排序 [英] 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
责任被完全移除.它应该通过对filter
的简单调用来完成,使用hardcodedOrdering.contains
作为谓词.
- 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屋!
查看全文