仅在for循环在Swift中执行完后,我该如何返回某些内容? [英] How do I return something only after a for-loop finishes executing in Swift?

查看:131
本文介绍了仅在for循环在Swift中执行完后,我该如何返回某些内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个时间段内每天记录的件数"并将其累加,因此我使用了for循环并在该时间段内进行迭代.但是,它似乎正在异步执行以下操作,因此仅返回0.这是我的代码:

I want to get the number of 'pieces' logged each day within a period and add it up, so I am using a for-loop and iterating through the period. However, it seems to be performing the following asynchronously, so 0 just gets returned. Here is my code:

func getPiecesInPeriod(period: Int, uid: String) -> Int{
    //period = #days
    var pieces = 0
    for i in 0..<period {
        let date = Date().addingTimeInterval(TimeInterval(-86400*i))
        Firestore.firestore().collection("Users").document(uid).collection("Log").document(getDayMonthYear(date: date)!).getDocument() {(document, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else if document?.get("total pieces") != nil {
                pieces += document!.get("total pieces") as! Int
            }
        }
    }
return pieces
}

我尝试使用完成处理程序:

I tried using a completion handler:

func getPiecesInPeriod(period: Int, uid: String, completion: @escaping (Int) -> Void) {
    //period = #days
    var pieces = 0
    for i in 0..<period {
        let date = Date().addingTimeInterval(TimeInterval(-86400*i))
        Firestore.firestore().collection("Users").document(uid).collection("Log").document(getDayMonthYear(date: date)!).getDocument() {(document, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else if document?.get("total pieces") != nil {
                pieces += document!.get("total pieces") as! Int
                print(document?.documentID)
                print(pieces)
            }
            completion(pieces)
        }
    }
}

但是无论我把"completion(pieces)"放在哪里,它似乎都行不通.有什么想法吗?

but no matter where I put the line 'completion(pieces)' it doesn't seem to work. Any ideas?

推荐答案

您将需要完成处理程序来执行此操作,然后需要确保仅在拥有所有期间的数据后才调用它.牢记这个定义,实际上并不难:如果您对已经装载了多少个计数器保持计数,就可以对照需要装载的总数进行检查.

You'll need the completion handler to do this, and then you need to make sure you only call it once you have the data for all periods. With that definition in mind, it's actually not that hard: if you keep a counter of how many pieces you've already loaded, you can check that against the total you need to load.

所以像这样:

func getPiecesInPeriod(period: Int, uid: String, completion: @escaping (Int) -> Void) {
    //period = #days
    var pieces = 0
    var count = 0
    for i in 0..<period {
        let date = Date().addingTimeInterval(TimeInterval(-86400*i))
        Firestore.firestore().collection("Users").document(uid).collection("Log").document(getDayMonthYear(date: date)!).getDocument() {(document, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else if document?.get("total pieces") != nil {
                pieces += document!.get("total pieces") as! Int
                print(document?.documentID)
                print(pieces)
            }
            if count++ = period {
                completion(pieces)
            }
        }
    }
}

这篇关于仅在for循环在Swift中执行完后,我该如何返回某些内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆