【问题标题】:Firebase what is the proper way to return handle and reference in SwiftFirebase 在 Swift 中返回句柄和引用的正确方法是什么
【发布时间】:2018-02-22 16:46:03
【问题描述】:

我从我的 fetch 函数中返回 DatabaseReferenceDatabasehandle 以便稍后分离监听器。但是,在 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)
}

【问题讨论】:

    标签: swift firebase asynchronous firebase-realtime-database swift4


    【解决方案1】:

    您将 fetchQuestions function 返回值与 Firebase closure 返回值混淆了——前者是 (DatabaseReference, DatabaseHandle) 但后者只是 Void ;)

    您的guard 实际上是从这个关闭返回 — 我现在使用 explicit 返回类型来明确(即{ (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 异步函数。这是一个非常常见的错误;)

    【讨论】:

    • 嗨@Paulo,我早就意识到了。但这使它更加清晰。谢谢!
    • @JGuo 很好,很高兴为您提供帮助;)
    • @PauloMattos 为什么像func fetchQuestions(completion: @escaping (Question?)-> (DatabaseReference, DatabaseHandle) ) 这样定义这个函数是非法的?基本上,返回 ref 和 handle 而不是 Void。不过,您的回答确实有效。
    猜你喜欢
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    相关资源
    最近更新 更多