【问题标题】:How do I return something only after a for-loop finishes executing in Swift?如何仅在 for 循环在 Swift 中完成执行后才返回某些内容?
【发布时间】:2020-06-30 21:07:44
【问题描述】:

我想获取一段时间内每天记录的“件数”并将其相加,因此我使用了一个 for 循环并遍历该时间段。但是,它似乎是在异步执行以下操作,因此只返回 0。这是我的代码:

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
}

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

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)
        }
    }
}

但无论我将“完成(件)”这一行放在哪里,它似乎都不起作用。有什么想法吗?

【问题讨论】:

    标签: swift firebase asynchronous completionhandler


    【解决方案1】:

    您需要完成处理程序来执行此操作,然后您需要确保仅在获得所有期间的数据后才调用它。考虑到这个定义,实际上并没有那么难:如果你记下你已经加载了多少件,你可以对照你需要加载的总数来检查。

    比如:

    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)
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多