【问题标题】:Cloud Firestore & Swift - Retrieve Document & assign fields to variables for processingCloud Firestore 和 Swift - 检索文档并将字段分配给变量以进行处理
【发布时间】:2019-01-04 19:40:58
【问题描述】:

我已经使用 get() 成功检索了单个文档的内容,但我似乎无法弄清楚如何将字段分配给变量。 https://firebase.google.com/docs/firestore/query-data/get-data

let docRef = db.collection("ask").document(uid!)

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }
}

输出:

文档数据:["q1": 1, "q2": 1, "q3": 0, "q4": 0]

所有值都是布尔值、真或假。

如何将文档中的字段分配给变量,以便我可以根据用户的回答执行代码:

var q1 = [?]
if q1 == false {
    //false code
} else {
    //true code
}

感谢您的帮助。

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    我会推荐这种方式:

    let docRef = db.collection("ask").document(uid!)
    
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            print("Document data: \(dataDescription)")
    
            let data = document.data()
    
            let q1 = data!["q1"]! as? Bool ?? true
    
            if q1 == false {
             //false code
            } else {
            //true code
            }
        } else {
            print("Document does not exist")
        }
    }
    

    【讨论】:

    • 这工作得很好,但我现在遇到了一个问题,即 if then 语句只执行 else 子句,但我正在处理它。您解决了将字段放入变量的问题,我确认通过打印命令有效。
    • 我明白了。这非常有效。您解决了将字段放入变量的问题,我通过 print 命令确认了这一点。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2011-10-26
    • 2018-08-10
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多