gpt4 book ai didi

arrays - Swift - 按另一个数组的属性对对象数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:46 25 4
gpt4 key购买 nike

我想根据对象数组与另一个对象数组共享的属性对对象数组进行排序

    struct GeneralComposition : Decodable {
let id, formId, relationId, fixedContentTypeId, separatorId: Int
let orderBy: Int

}
struct FixedContentType: Decodable {
let name, htmlType: String
let isEditable: Int
let typeId : String


}



var fixedContentType = [FixedContentType]()
var generalComposition = [GeneralComposition]()

GeneralComposition我得到了元素必须具有的顺序,orderBy ,然后取每一项的 fixedContentTypeID , 与 typeId 比较在FixedContentType获取此内容必须在屏幕上显示的顺序。

知道如何实现吗?

谢谢!

最佳答案

您可以为 generalCompositionfixedContentTypeID 构建字典:

let order = generalComposition.reduce(into: [Int: Int]()) { result, value in
result[value.fixedContentTypeId] = value.orderBy
}

您现在有一种有效的方法来查找 FixedContentType 对象数组中给定 typeIdorderBy 值。您可以使用它进行排序:

fixedContentType.sort {
(order[$0.typeId] ?? 0) < (order[$1.typeId] ?? 0)
}

顺便说一下,您的typeId 是一个String,而fixedContentTypeId 是一个Int。我假设这是在准备问题时引入的错字,并且它们实际上都是 Int。如果它们确实是不同的类型(这会很奇怪),解决方案将是相似的,尽管您必须进行一些转换。但我不想去那里,除非你确认这确实是你的模型。

但是,鉴于您的 typeId 确实是一个 String,您可以将您的字典设为 [String: Int]:

let order = generalComposition.reduce(into: [String: Int]()) { result, value in
result[String(value.fixedContentTypeId)] = value.orderBy
}

关于arrays - Swift - 按另一个数组的属性对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55191846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com