[英]Swift - Sort nested array based on a property
我有一個跟進集
struct Section {
let content: [Category]
func sortForItem3() -> [Category] {
// Sorting function
}
}
struct Category {
let items: [Item]
}
struct Item {
let value: String
}
let item1: Item = Item(value: "item1")
let item2: Item = Item(value: "item2")
let item3: Item = Item(value: "item3")
let item4: Item = Item(value: "item4")
let category1: Category = Category(items: [item1, item2])
let category2: Category = Category(items: [item3, item4])
let sectionContent: Section = Section(content:[category1, category2])
關於打印本節內容
print(sectionContent)
Section(content:
[SwiftPlayground.Category(items: [SwiftPlayground.Item(value: "item1"), SwiftPlayground.Item(value: "item2")]),
SwiftPlayground.Category(items: [SwiftPlayground.Item(value: "item3"), SwiftPlayground.Item(value: "item4")])]
)
我正在嘗試編寫一個排序條件,我需要在其中搜索值為“Item3”的項目,然后將該類別移至頂部。
當我打印內容時,預期的行為是:
print(sectionContent.sortForItem3())
所需的 output 是
Section(content:
[SwiftPlayground.Category(items: [SwiftPlayground.Item(value: "item3"), SwiftPlayground.Item(value: "item4")]),
SwiftPlayground.Category(items: [SwiftPlayground.Item(value: "item1"), SwiftPlayground.Item(value: "item2")])]
)
首先,您應該使 Item 符合Equatable
,其次將您的內容屬性從常量更改為變量。 將您的方法聲明為變異並刪除返回的 object。然后您只需要找到第一個包含項目的索引:
struct Category {
let items: [Item]
}
struct Item: Equatable {
let value: String
}
struct Section {
var content: [Category]
mutating func moveCategoryThatContainsItemToTop(_ item: Item) {
if let index = content.firstIndex(where: {$0.items.contains(item)}) {
content.insert(content.remove(at: index), at: 0)
}
}
}
let item1 = Item(value: "item1")
let item2 = Item(value: "item2")
let item3 = Item(value: "item3")
let item4 = Item(value: "item4")
let category1 = Category(items: [item1, item2])
let category2 = Category(items: [item3, item4])
var section = Section(content: [category1, category2])
print(section.content)
section.moveCategoryThatContainsItemToTop(item3)
print(section.content)
這將打印
[類別(項目:[項目(值:“item1”),項目(值:“item2”)]),
類別(項目:[項目(值:“item3”),項目(值:“item4”)])]
[類別(項目:[項目(值:“item3”),項目(值:“item4”)]),
類別(項目:[項目(值:“item1”),項目(值:“item2”)])]
如果您需要高效的解決方案? 那么如果業務邏輯允許,最好用字典替換 arrays 之一。 或者做這樣的事情:
var content: [Category]
for i = 0..<content.count {
var isFound = false
for item in content[i].items {
if item.value = "item3" {
let tmpContent = content[i]
content[i] = content[0]
content[0] = tmpContent
isFound = true
break
}
if isFound { break }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.