与Swift中的另一个数组相比,对数组进行重新排序 [英] Reorder array compared to another array in Swift

查看:151
本文介绍了与Swift中的另一个数组相比,对数组进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift中有一个包含一些对象ID的数组,而我有另一个包含这些对象及其ID的数组,所以是这样的:

I have one array in Swift containing some ids of objects, and I have another array containing these objects with their ids, so something like this:

class MyObject {
   let id: String
   ...
}

let ids: [String] = ...
let objects: [MyObject] = ...

现在,id数组以某种自定义顺序排序,我需要以相同顺序对对象数组进行排序.例如:

Now the array of ids is sorted in some custom order, and I need the array of objects to be sorted in the same order. So for example:

let ids: [String] = ["1", "2", "3"]
let objects: [MyObject] = [obj3, obj1, obj2]
// obj1.id = "1"
// obj2.id = "2"
// obj3.id = "3"
objects.reorder(template: ids) 
// Now objects = [obj1, obj2, obj3]

因此,我基本上需要实现此重新排序方法. 有谁有聪明的建议如何在Swift中做到这一点?我正在使用Swift 3,因此所有新API都可以使用.

So I basically need to implement this reorder method. Does anyone have a smart suggestion how to do this in Swift? I'm using Swift 3, so all the new APIs are available to me.

推荐答案

可以按照ids写作的顺序对objects进行排序

You can sort objects in order to follow the order in ids writing

let sorted = objects.sort { ids.indexOf($0.id) < ids.indexOf($1.id) }
// [{id "1"}, {id "2"}, {id "3"}]

另一个例子

let ids: [String] = ["3", "2", "1"]
let objects: [MyObject] = [MyObject(id: "3"), MyObject(id: "1"), MyObject(id: "2")]

let sorted = objects.sort { ids.indexOf($0.id) < ids.indexOf($1.id) }
// [{id "3"}, {id "2"}, {id "1"}]

这段代码在Swift 2.2中

This code is in Swift 2.2


Swift 4.2解决方案


Swift 4.2 solution

let sorted = objects.sorted { ids.index(of: $0.id)! < ids.index(of: $1.id)! }

这篇关于与Swift中的另一个数组相比,对数组进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆