我有跟进计划
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())
所需的输出是
Section(content:
[SwiftPlayground.Category(items: [SwiftPlayground.Item(value: "item3"), SwiftPlayground.Item(value: "item4")]),
SwiftPlayground.Category(items: [SwiftPlayground.Item(value: "item1"), SwiftPlayground.Item(value: "item2")])]
)
答案 0 :(得分:0)
首先,您应使Item符合Equatable
,然后将内容属性从常量更改为变量。将您的方法声明为mutate并删除返回的对象。然后,您只需要找到第一个索引,其中项目包含项目:
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)
这将打印
[类别(items:[Item(值:“ item1”),Item(值:“ item2”)]),
类别(items:[Item(值:“ item3”),Item(值:“ item4”)]))
[类别(items:[Item(值:“ item3”),Item(值:“ item4”)])),
类别(items:[Item(value:“ item1”),Item(value:“ item2”)]])]
答案 1 :(得分:0)
如果您需要高效的解决方案?那么如果业务逻辑允许,最好用字典替换其中一个数组。或执行以下操作:
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 }
}