我将从我的fetch函数返回DatabaseReference
和Databasehandle
,以便稍后分离侦听器。但是,在guard
语句的闭包内部,我无法返回(ref, handle)
,因为它位于句柄定义中。奇怪的是,如果我简单地放return
,Xcode就不会对我大喊大叫并编译好。这是对的吗?
我知道我可以改为DatabaseReference?
和Databasehandle?
并在守卫声明中返回(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)
}
答案 0 :(得分:1)
您的fetchQuestions
功能返回值与Firebase 闭包返回值相混淆 - 前者为(DatabaseReference, DatabaseHandle)
,后者仅为{ {1}};)
您的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:
Firebase 异步函数。这是非常常见的错误;)