我想根据对象数组与另一个对象数组共享的属性对对象数组进行排序
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
,与 进行比较
来获取该内容必须在屏幕上显示的顺序。FixedContentType
中的 >typeId
知道如何做到这一点吗?
谢谢!
最佳答案
您可以为 generalComposition
的 fixedContentTypeID
构建字典:
let order = generalComposition.reduce(into: [Int: Int]()) { result, value in
result[value.fixedContentTypeId] = value.orderBy
}
现在,您可以有效地在 FixedContentType
对象数组中查找给定 typeId
的 orderBy
值。您可以使用它进行排序:
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/