基于变量Swift 3中的公共值减少对象数组

时间:2017-03-02 05:22:44

标签: arrays swift

我有这堂课:

class Post {
    var key: String
    var uid: String
    var minutes: Int
    var name: String
    let ref: FIRDatabaseReference?

init(key: String, uid: String, minutes: Int, name: String){
    self.key = key
    self.uid = uid
    self.minutes = minutes
    self.name = name
    self.ref = nil
}

使用这个类我已经创建了一个对象数组,而我总共可以在几分钟内总计只有具有不同uid的元素的分钟数。

有人可以帮我指出正确的方向吗?

2 个答案:

答案 0 :(得分:2)

修改

我原来的答案似乎错过了你的问题,这就是你想要的:

let minutes = posts.reduce(([String : Int]())) { accumulator, value in
    var currentData = accumulator
    if accumulator.keys.contains(value.uid) {
        currentData[value.uid] = accumulator[value.uid]! + value.minutes
        return currentData
    } else {
        currentData[value.uid] = value.minutes
        return currentData
    }
}

这是仅用于总计唯一uid的分钟的游乐场代码:

 let posts = [Post(key: "key", uid: "0", minutes: 5, name: "name"), Post(key: "key", uid: "1", minutes: 5, name: "name"), Post(key: "key", uid: "1", minutes: 5, name: "name"), Post(key: "key", uid: "1", minutes: 5, name: "name"), Post(key: "key", uid: "3", minutes: 2, name: "name")]

 let count = posts.reduce((0, [String]())) { accumulator, value in
    if accumulator.1.contains(value.uid) {
        return accumulator
    } else {
        return (accumulator.0 + value.minutes, accumulator.1 + [value.uid])
    }
  }.0

“减少”可让您“重复”#34;你的帖子数组。您以分钟计数0和空uid数组开始。如果uid在那里,那么你不会在分钟计数中添加任何分钟,而是按原样保留数组。如果没有,则添加分钟并将字符串添加到uid字符串数组中。最后,通过获取元组的第一个元素(因此为.0)

来获得分钟计数

较短的版本是:

   let count = posts.reduce((0, [String]())) {
       return $0.1.contains($1.uid) ? $0 : ($0.0 + $1.minutes, $0.1 + [$1.uid])
   }.0

答案 1 :(得分:1)

使用新定义的问题,您要查找的内容将是:

let counts = values.reduce([String:Int]()) { acc, value in
    var copy = acc

    copy.updateValue((copy[value.uid] ?? 0) + value.minutes, forKey: value.uid)

    return copy
}