如何在数组中对自定义名称进行排序?

问题描述 投票:0回答:1

我有名称数组,我想按自定义排序对其进行排序。怎么办?

我的代码是:

var nameIndexArr = nameIndex.filter { $0.name == "IH" || $0.name == "LQ" || $0.name == "ID" }

我尝试排序:

nameIndexArr = nameIndexArr.sorted(by: { $0.name ?? "" < $1.name ?? "" })

但结果是ID、IH、LQ

我想要的是结果是IH,LQ,ID

如何根据我想要的结果对自定义进行排序?自定义排序的正确代码是什么,结果与我预期的相同?

arrays swift sorting
1个回答
-1
投票

为了实现您想要的自定义排序顺序,您可以定义一个自定义排序函数,按该顺序优先考虑“IH”、“LQ”和“ID”。以下是如何在 Swift 中做到这一点:

struct Item {
   let name: String
}

let nameIndexArr = [
   Item(name: "ID"),
    Item(name: "IH"),
    Item(name: "LQ")
]

let customOrder = ["IH", "LQ", "ID"]

let sortedArr = nameIndexArr.sorted {
    guard let index0 = customOrder.firstIndex(of: $0.name),
          let index1 = customOrder.firstIndex(of: $1.name) else {
         return false // Handle cases where name is not in customOrder
    }
    return index0 < index1
}

for item in sortedArr {
    print(item.name)
}
© www.soinside.com 2019 - 2024. All rights reserved.