不能从 for 循环中获取 return 值? Swift

Cannot return value from within for loop? Swift

我正在努力使用一个函数来获取选定的注释 (didSelect view:),检查数据库中所有注释坐标的坐标,以及 return 匹配注释的 uid。

但是,我认为我的 for 循环有误,因为它没有 returning 在 didSelect 函数中使用的值。 searchForEvent 函数在 didSelect view: 中调用,并根据数据库检查所选注释的纬度和经度。

代码如下:

 func searchForEvent(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> String? {
    var eventCoordinate: CLLocationCoordinate2D?
    var eventKey: String?
    var selectedEventKey = ""
    DataService.instance.REF_EVENTS.observeSingleEvent(of: .value, with: { (snapshot) in
        print("1")
        if let eventSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for event in eventSnapshot {
                eventKey = event.key
                print("\(eventKey)")
                print("2")
                if event.childSnapshot(forPath: "coordinate").value != nil  {
                    if let eventDict = event.value as? Dictionary<String, AnyObject> {
                        print("3")
                        //pull out value of key coordinate
                        let coordinateArray = eventDict["coordinate"] as! NSArray
                        print(coordinateArray)
                        eventCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees, longitude: coordinateArray[1] as! CLLocationDegrees)
                        print(eventCoordinate)
                        if (eventCoordinate?.latitude, eventCoordinate?.longitude) == (latitude, longitude) {
                            selectedEventKey = eventKey!
                            print("\(selectedEventKey), correct event")
                        } else {
                            print("incorrect event")
                        }
                    }
                }
            }
        }
    })
    return selectedEventKey

//        if selectedEventKey != nil {
//            print("4")
//            print("\(selectedEventKey)")
//            return selectedEventKey
//        } else {
//            print("empty key")
//            return nil
//        }
    }

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("selected")
    self.selectedAnnotation = view.annotation
    print(selectedAnnotation?.coordinate.latitude as Any)
    print(selectedAnnotation?.coordinate.longitude as Any)
    let lat = selectedAnnotation?.coordinate.latitude
    let lon = selectedAnnotation?.coordinate.longitude

    selectedAnnotationKey = searchForEvent(latitude: lat!, longitude: lon!)

    if selectedAnnotationKey == nil {
        print("no key")
    } else {
        print("found event final! \(selectedAnnotationKey)")
    }
}

didSelect函数中selectedAnnotationKey始终为nil :(

非常感谢任何帮助!

编辑

这是更新后的函数,感谢Sh_Khan的帮助。当它在调试区域打印正确的值时,它继续循环遍历数据库中的 "events" 并在结束后 returns nil 完成。

func searchForEvent(latitude: CLLocationDegrees, longitude: CLLocationDegrees , completion:@escaping(_ str:String?) -> Void ) {
    var eventCoordinate: CLLocationCoordinate2D?
    var eventKey: String?
    var selectedEventKey = ""
    DataService.instance.REF_EVENTS.observeSingleEvent(of: .value, with: { (snapshot) in
        print("1")
        if let eventSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for event in eventSnapshot {
                eventKey = event.key
                print("\(eventKey)")
                print("2")
                if event.childSnapshot(forPath: "coordinate").value != nil  {
                    if let eventDict = event.value as? Dictionary<String, AnyObject> {
                        print("3")
                        //pull out value of key coordinate
                        let coordinateArray = eventDict["coordinate"] as! NSArray
                        print(coordinateArray)
                        eventCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees, longitude: coordinateArray[1] as! CLLocationDegrees)
                        print(eventCoordinate)
                        if (eventCoordinate?.latitude, eventCoordinate?.longitude) == (latitude, longitude) {
                            selectedEventKey = eventKey!
                            print("\(selectedEventKey), correct event")
                            completion(selectedEventKey)
                        } else {
                            print("incorrect event")
                            completion(nil)
                        }
                    }
                }
            }
        }
    })
}


func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("selected")
    self.selectedAnnotation = view.annotation
    let lat = selectedAnnotation?.coordinate.latitude
    let lon = selectedAnnotation?.coordinate.longitude

    searchForEvent(latitude: lat!, longitude: lon!) { (str) in
        self.selectedAnnotationKey = str
        print("here it is \(str)")

        print(self.selectedAnnotationKey)
    }
}

调试打印输出:

selected
1
Optional("31E2932B-A037-4BB1-B93E-7504B61AC4E7")
2
3
(
    "-36.84745654404946",
    "174.7760903030886"
)
Optional(__C.CLLocationCoordinate2D(latitude: -36.847456544049464, longitude: 174.77609030308864))
incorrect event
here it is nil
nil
Optional("71173419-7E08-415C-9236-B1C8495A6BA9")
2
3
(
    "-36.86687593953122",
    "174.7585811441448"
)
Optional(__C.CLLocationCoordinate2D(latitude: -36.866875939531219, longitude: 174.75858114414478))

下面找到正确的事件,str和self.selectedAnnotationKey都是正确的,但是继续往下覆盖它!!!

71173419-7E08-415C-9236-B1C8495A6BA9, correct event
here it is Optional("71173419-7E08-415C-9236-B1C8495A6BA9")
Optional("71173419-7E08-415C-9236-B1C8495A6BA9")
Optional("7AC6429E-74B6-4A4E-A638-53981ACBFFBA")
2
3
(
    "-36.2429468",
    "175.3981152"
)
Optional(__C.CLLocationCoordinate2D(latitude: -36.242946799999999, longitude: 175.39811520000001))
incorrect event
here it is nil
nil

你需要完成

 func searchForEvent(latitude: CLLocationDegrees, longitude: CLLocationDegrees , completion:@escaping(_ str:String?) -> Void ) {
    var eventCoordinate: CLLocationCoordinate2D?
    var eventKey: String?
    var selectedEventKey = ""
    DataService.instance.REF_EVENTS.observeSingleEvent(of: .value, with: { (snapshot) in
        print("1")
        if let eventSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for event in eventSnapshot {
                eventKey = event.key
                print("\(eventKey)")
                print("2")
                if event.childSnapshot(forPath: "coordinate").value != nil  {
                    if let eventDict = event.value as? Dictionary<String, AnyObject> {
                        print("3")
                        //pull out value of key coordinate
                        let coordinateArray = eventDict["coordinate"] as! NSArray
                        print(coordinateArray)
                        eventCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees, longitude: coordinateArray[1] as! CLLocationDegrees)
                        print(eventCoordinate)
                        if (eventCoordinate?.latitude, eventCoordinate?.longitude) == (latitude, longitude) {
                            selectedEventKey = eventKey!
                            print("\(selectedEventKey), correct event")
                            completion(selectedEventKey)
                        } else {
                            print("incorrect event")
                            completion(nil)
                        }
                    }
                }
            }
        }
    })
 }

//

打电话

searchForEvent(//value1,//value2) { (str) in
  print(str)
}

你需要一个完成处理程序