gpt4 book ai didi

arrays - 根据变量 Swift 3 中的公共(public)值减少对象数组

转载 作者:可可西里 更新时间:2023-11-01 00:57:29 24 4
gpt4 key购买 nike

我有这门课:

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 的元素的分钟数。

有人能帮我指明正确的方向吗?

最佳答案

编辑

我原来的回答似乎没有捕获你的问题,这就是你想要的:

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 的分钟数的 playground 代码:

 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

reduce 允许您“迭代”您的帖子数组。您从 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

关于arrays - 根据变量 Swift 3 中的公共(public)值减少对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com