Swift函数返回为时过早

时间:2018-08-01 18:58:19

标签: swift xcode function asynchronous

在以下代码中,该函数将在 checkDayEqualsToDoc 函数返回布尔值并更改“ Var”之前返回“ Var”。我试图在很多地方寻找答案,但我一直看到相同的东西...使用闭包...使用补全...等等。在这种情况下,这些东西是正确的吗?如果是这样,我将如何实施?

func dotMarker(shouldShowOnDayView dayView: DayView) -> Bool {
    var Var:Bool = false
    let dDate = dayView.date.convertedDate()
    DispatchQueue.main.async {
        self.checkDayEqualsToDoc(date: dayView.date.convertedDate()!){ (bool, error) in
            Var = bool
        }
    }
    return Var
}

这是 checkDayEqualsToDoc 函数:

func checkDayEqualsToDoc(date: Date, completionHandler:@escaping (Bool, Error?) -> Void){
    var Variable = false
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: date)
    let btRef = db.collection("bomtracking")

    let myDate = date
    let startOfDate = myDate.startOfDay
    let endOfDate = myDate.endOfDay
    let dateAtBeginning = date.firstSecondInDay()
    let dateAtEnd = date.lastSecondInDay()
    let query = btRef
        .whereField("UID", isEqualTo: UID)
        .whereField("timestamp", isGreaterThan: dateAtBeginning)
        .whereField("timestamp", isLessThan: dateAtEnd)

    DispatchQueue.main.async {
        query.getDocuments(){ (querySnapshot, err) in
            if let err = err {
                print("error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents{
                    let curValid = document.get("valid")
                    let curValidA = Bool(curValid as! Bool)
                    if curValidA == true {
                        let curdoc = document.get("timestamp")
                        let curdocDate = self.dateConversion(curdoc as! Date)
                        let dateConverted = self.dateConversion(date)
                        if curdocDate == dateConverted {
                            Variable = true
                            break
                        }
                        else {
                            Variable = false
                        }
                    }
                }
                completionHandler(Variable, nil)
            }
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

当一个函数是异步的时,您不想返回该值,而是想在完成时将其传递回去。

func dotMarker(shouldShowOn dayView: DayView, completion: @escaping (Bool)->Void) {
    let dDate = dayView.date.convertedDate()
    DispatchQueue.main.async {
        self.checkDayEqualsToDoc(date: dayView.date.convertedDate()!){ (bool, error) in
            completion(bool)
        }
    }
}

是这样的。 checkDaysEqualsToDoc完成后,将调用其自己的完成,这就是(bool, error) in的来源。在该完成中,您拥有希望dotMarker“返回”的值,因此您使用该bool值调用完成处理程序。

不过有两件事:

  1. 为什么要将checkDayEqualsToDoc放在异步线程中?

  2. 变量名应始终以小写开头,并且应比Var

  3. 更具描述性