我有一個問題,在我看來這不應該是一個問題。Swift沒有在回報聲明中設置一個值
當我加載這個'簡單'功能時,它應該返回數據庫中的用戶。
- returns usersDictionary: All the users in a dictionary
*/
func getAllUsers() -> Dictionary<String, AnyObject> {
var usersDict = Dictionary<String, AnyObject>()
if userIsLoggedIn() == true{
FIRDatabase.database().reference().child("users").observeSingleEvent(of: .value, with: { (snapshot) in
if let userDictionary = snapshot.value as? [String:AnyObject]{
for user in userDictionary{
usersDict.updateValue(user.value as AnyObject
, forKey: user.key as String)
}
print("TEST")
print(usersDict)
}
print("TEST2")
print(usersDict)
})
print("TEST3")
print(usersDict)
return usersDict
}
return usersDict
}
但是它不返回值usersDict,只是空的,因爲它打印輸出測試和TEST2 usersDict的值是奇怪。
但是Test3仍然是空的,這怎麼可能?如果我查看控制檯,它首先測試Test3,然後測試然後測試test2。
這是控制檯打印:
TEST3
[:]
TEST
"ZuUiTSu142P5NTc9VfekRbuFcny2": {
address = "testAddress";
email = "[email protected]";
name = "testuser";
phonenumber = "1234567890";
rol = Customer;
}]
TEST2
"ZuUiTSu142P5NTc9VfekRbuFcny2": {
address = " testAddress ";
email = " [email protected] ";
name = "testuser";
phonenumber = "1234567890";
rol = Customer;
}]
這並不奇怪,在所有:'observeSingleEvent'工作** **異步的
只是我如何能做到這一點,我隨處現在把它叫做一個簡單的例子數據將在稍後的封閉中返回。你需要一個完成處理程序,直接返回是不可能的。 – vadian
[在Swift函數中從異步調用中返回數據]的可能副本(http://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – Keiwan