【发布时间】:2021-03-27 03:26:19
【问题描述】:
我正在尝试设置一个辅助函数。这个应该返回搜索历史的结果。 但它总是返回一个空数组。控制台中的打印显示了一个完整的数组。看来,return 执行得早了。
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
}
【问题讨论】:
-
将
print(searchHistory)替换为print("Inside closure: \(searchHistory)")并将return searchHistory替换为print("Outside and after the closure: \(searchHistory)"); return searchHistory应该先打印哪个?哪一个是现实印出来的?您缺少异步概念。寻找应该会给你很多答案的“Swift + Async + Closure”。 -
在封闭内打印 ["Henrik","Mirco","Tim"] 在外面 []
标签: swift xcode function return