0

I wanna change global variable 'isRiskLocation' in docRef.getDocuments { ~ }

Can you give me advice?

func checkRiskLocationAleadyExist(database: Firestore!, latitude: Double, longitude: Double) -> Bool {
    
    var isRiskLocationExist: Bool = false
    
    let docRef = database.collection("collectionName")
        .whereField("latitude", isEqualTo: latitude)
        .whereField("longitude", isEqualTo: longitude)
    docRef.getDocuments { (querysnapshot, error) in
        
        guard let data = querysnapshot?.documents else {return }
        
        isRiskLocationExist = data.isEmpty  // This is not working. I hope to change 'isRiskLocation' value depending on "data.isEmpty"
    }
    print(isRiskLocationExist)   <-- This is only print "false" 
    return isRiskLocationExist
}
  • 1
    you are mixing asynchronous work with synchronous, you should read about completion handlers. – lorem ipsum Nov 08 '22 at 13:58
  • The problem is not so much **where** you access `isRiskLocationExist` as much as **when** you access it. Data is loaded from Firestore (and most modern cloud APIs) asynchronously, which means that your `isRiskLocationExist = data.isEmpty` runs later than `print(isRiskLocationExist)`. Any code that needs the data, needs to be inside the completion handler, be called from there, or otherwise synchronized. See https://stackoverflow.com/questions/71972316/addsnapshotlistener-triggers-all-the-function-dependent-to-it/71972457#71972457 for more – Frank van Puffelen Nov 08 '22 at 14:27
  • Thanks I'll search asynchronous – swiftAmatuer Nov 09 '22 at 03:02

0 Answers0