我正在从我的 fetch 函数中返回 DatabaseReference
和 Databasehandle
以便稍后分离监听器。但是,在 guard
语句的闭包内,我无法返回 (ref, handle)
因为它在句柄定义内。奇怪的是,如果我简单地输入 return
,Xcode 不会对我大喊大叫并且编译正常。这是正确的吗?
我知道我可以用 DatabaseReference?
和 Databasehandle?
代替,并在 guard 语句中返回 (nil, nil)
。但对我来说更有意义的是,无论获取是否成功,都应该返回一个引用和一个句柄。
func fetchQuestions(completion: @escaping (Question?)->()) -> (DatabaseReference, DatabaseHandle)
{
let ref = root.child("timeline").child(uid)
let handle = ref.observe(.childAdded, with: { (snapshot) in
var question: Question?
defer { completion(question) }
guard let dict = snapshot.value as? [String: Int] else {
return // Is this correct?
}
...
})
return (ref, handle)
}
最佳答案
您将 fetchQuestions
function 返回值与 Firebase closure 返回值混淆了——前者是 (DatabaseReference, DatabaseHandle)
但后者只是 Void
;)
你的 guard
实际上正在从这个闭包中返回
— 我现在使用 显式 返回类型来明确(即 { (snapshot) -> Void ...
):
func fetchQuestions(completion: @escaping (Question?)->()) -> (DatabaseReference, DatabaseHandle)
{
let ref = root.child("timeline").child(uid)
let handle = ref.observe(.childAdded, with: { (snapshot) -> Void in
var question: Question?
defer { completion(question) }
guard let dict = snapshot.value as? [String: Int] else {
return // Is this correct? Yes! (returning from Void closure)
}
...
})
return (ref, handle)
}
此闭包作为最后一个参数(即 with:
)传递给 observe
Firebase 异步 函数。这是一个非常的常见错误;)
关于swift - Firebase 在 Swift 中返回句柄和引用的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48932878/