优雅的方法将[[(int,string)]]组合到[(int,string)]中



我正在使用swift 4,xcode 9。

具体来说,我有一个数组数组[[(int,string)],其中int是级别,字符串是名称 项目...使用.joined(saparator:";")。<<<<

数据可能看起来像这样:

[[1,"My Name;Item1;Item2"], [(5,"My Name;Item2;Item3"), (3,"My Second Name;Item1")]]

我想组合内部阵列,以便:

  1. int添加了基于名称的匹配项(最多";")
  2. 字符串添加后续项目(如果尚未出现)

结合上述示例应该导致此:

[(6,"My Name;Item1;Item2;Item3"), (3,"My Second Name;Item1")]

即。输入是[[(Int, String)]],输出为[(Int, String)]

目前,我可以通过一组相当复杂的循环来实现这一目标。使用大数据集,这会导致明显的性能下降。在我要求时,是否有一种优雅/简单的方法可以组合这些阵列?

谢谢您的任何指导!

(通常我会发表评论,因为它没有回答这个问题,但是要确切地解释您应该如何更改此问题是值得的。)

这肯定是可能的,但不要。答案是用一系列结构代替。根据您的数据描述:

struct Element {
    let rank: Int
    let name: String
    let items: Set<String> // Since you seem to want them to be unique and unordered
}
let elements: [[Element]] =
    [[Element(rank: 1, name: "My Name", items: ["Item1", "Item2"])],
     [Element(rank: 5, name: "My Name", items: ["Item2", "Item3"]),
      Element(rank: 3, name: "My Second Name", items: ["Item1"])]]
// You want to manage these by name, so let's make key/value pairs of all the elements
// as (Name, Element)
let namedElements = elements.joined().map { ($0.name, $0) }
// Now combine them as you describe. Add the ranks, and merge the items
let uniqueElements =
    Dictionary<String, Element>(namedElements,
                                uniquingKeysWith: { (lhs, rhs) -> Element in
                                    return Element(rank: lhs.rank + rhs.rank,
                                                   name: lhs.name,
                                                   items: lhs.items.union(rhs.items))
    })
// The result is the values of the dictionary
let result = uniqueElements.values
// Element(rank: 6, name: "My Name", items: Set(["Item3", "Item2", "Item1"]))
// Element(rank: 3, name: "My Second Name", items: Set(["Item1"]))

最新更新