Finish asynchronous task in Firebase with Swift

I am trying to write a function that will return an array of all my workers, but it is returning before retrieving the data from firebase

here is my code:

func getWorkersList() -> ([Worker])
{
    let workersInfoRef = ref.childByAppendingPath("countries/\(userCountry)/cities/\(userCity)/workers/\(workFieldToRecieve)/")

    var workerList = [Worker]()
        workersInfoRef.queryOrderedByChild("name").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        print(snapshot.childrenCount)
        for rest in snapshot.children.allObjects as! [FDataSnapshot]{

            let workerInfo = Worker(uid: rest.value["uid"] as! String, name: rest.value["name"] as! String, city: rest.value["city"] as! String, profession: rest.value["profession"] as! String, phone: rest.value["phone"] as! String, email: rest.value["email"] as! String, country: rest.value["country"] as! String)
            workerList.append(workerInfo)

        }
        }) { (error) in
            print(error.description)
    }

    print(workerList.count)
    return workerList

}

Solution 1:

This is not tested... I just coded it up on the fly to give you the general idea

add a completion block/callback to your function...

func getWorkersList(callback: ((data:[Worker]) ->Void )) {
    let workersInfoRef = ref.childByAppendingPath("countries/\(userCountry)/cities/\(userCity)/workers/\(workFieldToRecieve)/")

    var workerList = [Worker]()
    workersInfoRef.queryOrderedByChild("name")
       .observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        print(snapshot.childrenCount)
        for rest in snapshot.children.allObjects as! [FDataSnapshot]{

            let workerInfo = Worker(uid: rest.value["uid"] as! String, name: rest.value["name"] as! String, city: rest.value["city"] as! String, profession: rest.value["profession"] as! String, phone: rest.value["phone"] as! String, email: rest.value["email"] as! String, country: rest.value["country"] as! String)
            workerList.append(workerInfo)

        }
        print(workerList.count)
        callback(workerList)

   }) { (error) in  print(error.description) }
}

pass in the completion block..

getWorkersList(callback: { (data:[Worker]) -> Void in 
    print(data)
})