首页 > 解决方案 > 根据来自另一个数组 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]
]

标签: arraysswiftsortingarraylist

解决方案


您可以在 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)]

推荐阅读