首页 > 解决方案 > Cloud Firestore Swift:如何在标签中显示数字字段

问题描述

我有一个来自 Cloud Firestore 的数字字段,需要在标签中显示为字符串。

通常,如果字段是字符串,我可以执行这段代码

db.collection("users").document(uid ?? "UID not yet loaded in viewDidLoad()")
    .addSnapshotListener { snapshot, error in
        if error != nil {
            print(error ?? "Couldn't update text field TextUser according to database")
        } else {
            if let dbUsername = snapshot?["username"] as? String {
                self.textUser?.text = dbUsername
            }

之所以有效,是因为文档中的“用户名”是一个值字符串。但这不起作用,因为文档中的“现金”是一个价值数字。

if let dbCash = snapshot? ["cash"] as? String {
    self.labeCash?.text = dbCash
}

我可能只需要将数字(无论他们使用什么类型)转换为字符串。但我该怎么做呢?谢谢!

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


你能试一下吗

if let dbCash = snapshot? ["cash"] as? NSNumber {
   self.labeCash?.text = dbCash.stringValue
}

推荐阅读