【发布时间】:2020-04-24 20:41:51
【问题描述】:
我有一个数组tags,其中包括几个元素id 和name。我还有一个数组order,其中存在tags 中的一些 元素。这是我想要实现的目标:
-
tags中的所有元素都应按照order排序。 -
order中不存在的元素应按字母顺序排列在order中存在的元素之后。
我已经使用for 循环解决了它(代码在 Playground 中运行):
import Foundation
import UIKit
struct Tag: Identifiable {
var id: Int
var name: String
}
// Ccc > Bbb > Aaa > Ddd > Eee
var tags = [Tag(id: 1000, name: "Ccc"), Tag(id: 1001, name: "Bbb"), Tag(id: 1002, name: "Aaa"), Tag(id: 1003, name: "Ddd"), Tag(id: 1004, name: "Eee")]
// Eee > Ddd > Ccc > Bbb > Aaa
tags.sort(by: { $0.name < $1.name })
// Bbb > Ddd
var idOrdering = [1001, 1003]
// Bbb > Ddd > Aaa > Ccc > Eee
for orderIndex in idOrdering.indices {
// Get tag id.
let tagId = idOrdering[orderIndex]
let tagIndex = tags.firstIndex(where: { $0.id == tagId })
// Remove tag from original array and place it according to the `order`.
let removedTag = tags.remove(at: tagIndex!)
tags.insert(removedTag, at: orderIndex)
}
// Print the result.
tags.forEach {
print($0.name)
}
原来tags中元素的顺序是Ccc > Bbb > Aaa > Ddd > Eee。其中两个名为Bbb和Ddd的元素应根据order排序,即Bbb > Ddd。其余的应按字母顺序排列。换句话说,最终结果应该是Bbb > Ddd > Aaa > Ccc > Eee。虽然上面的for 循环有效,但我怎样才能更有效地解决这个问题?
【问题讨论】:
-
似乎我的这个答案与您想要的完全匹配:stackoverflow.com/a/43056896/3141234
-
这个问题中的
UUIDs 很笨拙,会分散核心问题的注意力。我建议你用小的Ints 替换它们,并生成一个预期的output数组。 -
x = x.sorted { ... }是一种不好的做法。要么只使用就地变体 (x.sort { ... }),要么更好的是,只需创建一个新变量。 -
根据反馈更新代码。