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

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

问题描述

我在 Swift 中有一个包含一些对象 ID 的数组,我有另一个包含这些对象及其 ID 的数组,如下所示:

class MyObject {让 ID:字符串...}让 ID:[字符串] = ...让对象:[MyObject] = ...

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

let ids: [String] = ["1", "2", "3"]让对象:[MyObject] = [obj3, obj1, obj2]//obj1.id = "1"//obj2.id = "2"//obj3.id = "3"objects.reorder(模板:ids)//现在对象 = [obj1, obj2, obj3]

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

解决方案

您可以对 objects 进行排序,以便按照 ids 书写的顺序

let sorted = objects.sort { ids.indexOf($0.id) 

另一个例子

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

<块引用>

此代码在 Swift 2.2 中

<小时>

Swift 4.2 解决方案

let sorted = objects.sorted { ids.index(of: $0.id)!<ids.index(of: $1.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] = ...

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]

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.

解决方案

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"}]

Another example

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"}]

This code is in Swift 2.2


Swift 4.2 solution

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

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

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