如何通过Firebase返回在数据服务类中创建的对象? [英] How can I return an object that I create in my data service class through Firebase?
问题描述
我试图遵守MVC惯例,并将所有网络代码保留在我的应用程序中使用的数据服务类之内.在一个屏幕上,我有需要显示的用户名和用户名.更新此函数时,我正在调用此函数:
I am trying to adhere to MVC practices and keep all the network code inside the data service class that I am using in my app. On one screen I have the user's name and username that needs to be displayed. When updating this, I am calling this function:
func grabUserData() -> User {
REF_USERS.child(getCurrentUID()).observeSingleEvent(of: .value) {
(snapshot) in
if let userDict = snapshot.value as? Dictionary<String, String> {
let user = User(
first: userDict["firstName"]!,
last: userDict["lastName"]!,
username: userDict["username"]!
)
return user
}
}
}
但是尝试返回用户时出现错误!它说:
But I am getting an error trying to return the user! It says:
void函数中非预期的非void返回值.
Unexpected non-void return value in void function.
但是该功能显然不是无效的.那我该怎么办?
But the function clearly isn't void. So what do I do?
推荐答案
您正在将您的grabUserData
功能返回值与Firebase closure 返回值混淆—前者是User
,但后者是Void
;)
You are confusing your grabUserData
function return value with the Firebase closure return value — the former is User
but the latter is Void
;)
您实际上正在从此关闭中返回 —我现在使用的是 explicit 返回类型,以便清楚:
You are actually returning from this closure — I'm now using a explicit return type to be clear:
{
(snapshot) -> Void in
if let userDict = snapshot.value as? Dictionary<String,String> {
let user = User(
first: userDict["firstName"]!,
last: userDict["lastName"]!,
username: userDict["username"]!
)
return user
}
}
作为最后一个参数传递给observeSingleEvent
Firebase函数.这是一个非常常见错误;)
which is passed as the last argument to the observeSingleEvent
Firebase function. This is a very common mistake ;)
完成处理程序.这里的标准模式是通过补全处理程序 返回所需的User
.该解决方案很好地模拟了网络请求(例如Firebase数据库调用)的异步性质.例如:
Completion handler. A standard pattern here is to return the desired User
via a completion handler instead. This solution nicely models the asynchronous nature of network requests such as Firebase database calls. For instance:
func grabUserData(completion: @escaping (User?) -> Void) {
REF_USERS.child(getCurrentUID()).observeSingleEvent(of: .value) {
(snapshot) in
if let userDict = snapshot.value as? Dictionary<String, String> {
let user = User(
first: userDict["firstName"]!,
last: userDict["lastName"]!,
username: userDict["username"]!
)
completion(user) // Returns user!
} else {
completion(nil) // User not found!
}
}
}
最后,在您的数据服务客户端代码中,像这样调用它:
Finally, in your data service client code, call it like this:
grabUserData() {
(user) in
if let user = user {
print("Grabbed user: \(user)")
} else {
print("User not found!")
}
}
这篇关于如何通过Firebase返回在数据服务类中创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!