How to make a dictionary data from Firestore conform to sequence? I want use one of the fields and add the Integers together

huangapple go评论60阅读模式
英文:

How to make a dictionary data from Firestore conform to sequence? I want use one of the fields and add the Integers together

问题

I have a compactmap of the data from the cloud Firestore, however I need access to just one of the variables and iterate over it to add up the Integers stored there.
My data contains Dates and does not conform to Sequence and I am struggling to find a solution

My data:

我有一个来自云Firestore的紧凑映射数据,但我需要访问其中一个变量,并迭代访问它以累加存储在那里的整数。
我的数据包含日期,不符合序列,并且我正在努力寻找解决方案

我的数据:

Firestore fetch:

Firestore获取:

I need a way to access the numDays data and add together all the values for all the data saved.
我需要一种访问numDays数据并将保存的所有数据的所有值相加的方法。

I have tried for loops but as Travel doesn't conform to Sequence I cannot do that.
我尝试了for循环,但由于Travel不符合序列,我无法这样做。

I then have the viewModel:
然后我有viewModel:

@Published var travel: Loadable<[Travel]> = .loading

@Published var travel: Loadable<[Travel]> = .loading

func fetchPosts() {

func fetchPosts() {

Task {

任务 {

do {

做 {

travel = .loaded(try await datesRepository.fetchData())

travel = .loaded(try await datesRepository.fetchData())

} catch {

}捕获{

print("[ViewModel] Cannot fetch posts: (error)")

print("[ViewModel] 无法获取帖子:\(error)")

travel = .error(error)

travel = .error(error)

}

}

Any attempts to do a for loop on this data hasn't worked.
在这些数据上进行for循环的任何尝试都没有成功。
Please help
请帮助

英文:

I have a compactmap of the the data from the cloud Firestore, however I need access to just one of the variables and iterate over it to add up the Integers stored there.
My data contains Dates and does not conform to Sequence and I am struggling to find a solution

My data:

struct Travel: Identifiable, Equatable, Codable {
    var id = UUID()
    var reason: String
    var date: Date
    var numDays: Int

Firestore fetch:

func fetchData() async throws -&gt; [Travel] {
        guard let uid = Auth.auth().currentUser?.uid else { return [] }
        let snapshot = try await reference1.document(uid).collection(&quot;dates&quot;)
            .order(by: &quot;date&quot;, descending: true)
            .getDocuments()
        return snapshot.documents.compactMap { document in
            try! document.data(as: Travel.self)
        }
    }

I need a way to access the numDays data and add together all the values for all the data saved.

I have tried for loops but as Travel doesn't conform to Sequence I cannot do that.

I then have the viewModel:

    @Published var travel: Loadable&lt;[Travel]&gt; = .loading
    
    
        func fetchPosts() {
                Task {
                    do {
                        travel = .loaded(try await datesRepository.fetchData())
                    } catch {
                        print(&quot;[ViewModel] Cannot fetch posts: \(error)&quot;)
                        travel = .error(error)
                    }
                }
            }

Any attempts to do a for loop on this data hasn't worked.
Please help

答案1

得分: 0

如果我理解问题正确的话,你想要取出一个包含Travel对象的数组,提取出numDays的值并将它们相加,对吗?如果是这样的话,你可以使用.reduce

let travelArray: [Travel] = ...
let totalDays = travelArray.reduce(0) { $0 + $1.numDays }

这句话的意思是:“取出你的数组,在0的基础上执行reduce操作,将每个Travel对象的numDays值加到reduce中的运行总数,并返回总数。”

英文:

If I understand the problem correctly, you want to take an array of Travel objects, pull out the value of numDays and add all of them together? If so, you can use .reduce.

let travelArray: [Travel] = ...
let totalDays = travelArray.reduce(0) { $0 + $1.numDays }

This translates to "take your array and perform a reduce starting at 0, adding each Travel object's numDays value to the running total in reduce and return the total."

答案2

得分: 0

你可以创建一个函数,传入一个包含你的旅行对象的数组,并使用.reduce方法来累加天数并返回。类似这样:

func calculateTotalNumDays(travels: [Travel]) -> Int {
    let totalNumDays = travels.reduce(0) { (result, travel) in
        return result + travel.numDays
    }
    return totalNumDays
}

//示例
do {
    let fetchedTravels = try await datesRepository.fetchData()
    let totalNumDays = calculateTotalNumDays(travels: fetchedTravels)
    print("Total numDays: \(totalNumDays)")
} catch {
    print("Error fetching data: \(error)")
}

(Note: The code example provided in the original text is already in Swift, so there's no need to translate the code itself.)

英文:

You can create a function that you pass in an array of your Travel objects and use the .reduce method to sum up the days and return it if you want. Something like this:

func calculateTotalNumDays(travels: [Travel]) -&gt; Int {
    let totalNumDays = travels.reduce(0) { (result, travel) in
        return result + travel.numDays
    }
    return totalNumDays
}

//Example
do {
    let fetchedTravels = try await datesRepository.fetchData()
    let totalNumDays = calculateTotalNumDays(travels: fetchedTravels)
    print(&quot;Total numDays: \(totalNumDays)&quot;)
} catch {
    print(&quot;Error fetching data: \(error)&quot;)
}

huangapple
  • 本文由 发表于 2023年5月11日 00:25:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定