将数组数据合并为唯一值

时间:2019-06-21 23:21:00

标签: arrays swift

在Swift中,如果给定一个包含int和字符串的结构,则可以基于字符串值(感觉像键,值问题)对int求和

给定:

struct Structure {
    let number: Int
    let text: String
}

var arrayOfStructs: [Structure] = [
    Structure(number: 3, text: "foo"),
    Structure(number: 5, text: "bar"),
    Structure(number: 7, text: "foo")
    ]

arrayOfStructs.count()==3

输出一个数组,其中元素0和2实际上是“求和”的结果,


arrayOfStructs[0] == Structure(number:10, text: "foo")
arrayOfStructs[1] == Structure(number:5, text: "bar")
arrayOfStructs.count() == 2 

1 个答案:

答案 0 :(得分:0)

这是将结构数组简化为新数组的一种方法,其中每个text值都出现一次,而number值是对应的text值的和。

struct Structure{
    let number: Int
    let text: String
}

var arrayOfStructs: [Structure] = [
    Structure(number: 4, text: "A"),
    Structure(number: 2, text: "B"),
    Structure(number: 5, text: "C"),
    Structure(number: 7, text: "A"),
    Structure(number: 3, text: "C"),
    Structure(number: 1, text: "A"),
    Structure(number: 6, text: "C"),
]

let newStructs = arrayOfStructs
                     .reduce(into: [String: Int]()) { $0[$1.text, default: 0] += $1.number }
                     .map { Structure(number: $0.value, text: $0.key) }
print(newStructs)