0

I am trying to set a helper function. This one should return the results of search history. But it returns an empty Array always. The print in Console shows me a full array. It seems like, the return executed to early.

 static func getSearchHistorySorted(userID: String) -> [String]{
            var searchHistory = [String]()
                databaseReference.child("\(userID)/searchhistory").queryOrderedByValue().queryLimited(toFirst: 6).observeSingleEvent(of: .value, with: { (snapshot) in
                    if let entries = snapshot.value as? [String : Double]  {
                        let myArr = Array(entries.keys)
                        let sortedKeys = myArr.sorted() {
                            let obj1 = entries[$0] // get ob associated w/ key 1
                            let obj2 = entries[$1] // get ob associated w/ key 2
                            return obj1! < obj2!
                        }
                        searchHistory = sortedKeys
                        print(searchHistory)
                    }
                })
            return searchHistory
        }
  • Replace `print(searchHistory)` with `print("Inside closure: \(searchHistory)")` and `return searchHistory` with `print("Outside and after the closure: \(searchHistory)"); return searchHistory` Which one should be printed first? Which one is printed in reality? You are missing the asynchrone concept. Look for "Swift + Async + Closure" that should give you plenty of answers. – Larme Dec 16 '20 at 13:00
  • print inside closure["Henrik","Mirco","Tim"] outside [] – Michael Müller Dec 16 '20 at 13:11

1 Answers1

0

You can't do what you are trying to do. The function observeSingleEvent(of:with:) is asynchronous. It takes a closure (code to execute once it is complete) and then returns immediately.

You need to refactor your code to take a completion handler. This comes up all the time. See this question and answer for an example:

Async return function in Swift 4

Duncan C
  • 128,072
  • 22
  • 173
  • 272