arrays - 根据来自另一个数组 Swift 的顺序对数组进行排序
问题描述
我有以下两个数组:
fetchedProducts = [
[name: "productName20", id: 20],
[name: "productName3", id: 3],
[name: "productName1", id: 1]
]
sortedProducts = [
[productName1: "1"], // I know the numbers here are string; I need them to be string
[productName20: "20"],
[productName3: "3"]
]
现在我需要fetchedProducts
根据的顺序进行排序,sortedProducts
所以它最终看起来像下面这样:
fetchedProducts = [
[name: "productName1", id: 1],
[name: "productName20", id: 20],
[name: "productName3", id: 3]
]
解决方案
您可以在 Swift 中尝试以下操作。请注意 Swift 中的字典是无序的,因此您必须将数组用于有序集合:
let fetchedProducts = [
(name: "productName20", id: 20),
(name: "productName3", id: 3),
(name: "productName1", id: 1),
]
let sortedProducts = [
("productName1", "1"),
("productName20", "20"),
("productName3", "3"),
]
let sortedFetchedProducts = sortedProducts
.compactMap { s in
fetchedProducts.first(where: { s.1 == String($0.id) })
}
print(sortedFetchedProducts)
// [(name: "productName1", id: 1), (name: "productName20", id: 20), (name: "productName3", id: 3)]
推荐阅读
- here-api - 清除站点数据中断映射 - IndexedDB 未处理关闭的连接
- angular - 如何为以 Azure AD 作为身份提供者的 Angular 7.x 应用程序实施基于 SAML 的身份验证?
- windows - 如何将批处理文件的结果输出到与输入文件同名的文件夹中?
- jquery - 如何在summernote编辑器中插入bootstrap col,我想将它添加到来自数据库的数据中
- c - double 5.2 如何在二进制文件中表示?
- php - 将图像上传到 imgur API 的错误请求 400
- spring - Spring Data Jpa Repository 可以用来创建复杂的查询吗?
- node.js - 如何更新 Node.js + Nginx 站点
- python - 使用文字字符串插值或 f 字符串时的 SyntaxError
- android - 如何将数据返回到被 Android 破坏的 Activity