【问题标题】:Cannot subscript a value of type 'String' with an index of type 'String' Swift Error无法使用“字符串”类型的索引为“字符串”类型的值下标 Swift 错误
【发布时间】:2019-11-29 08:12:48
【问题描述】:

首先,其他问题和我的不一样。 在从 Firebase Firestore 检索数据后,我试图从 Swift Xcode 中的数据中获取单个值。相反,它给出了一个错误:

不能用“String”类型的索引为“String”类型的值下标

ref.getDocument { (document, err) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing: )) ?? "nil"
                print ("Cached document data: \(dataDescription)")
                profilename?.text = dataDescription["name"] as! String
            } else {
                print ("Document doesn't exist")
            }
        }

错误发生在

profilename?.text = dataDescription["name"] as! String

线。

dataDescription 的打印是:

缓存的文档数据:["email": test2@gmail.com, "name": Test2, "phone": 408-222-2222]

谁能帮我解决这个问题?

【问题讨论】:

  • 错误清楚地表明dataDescription 是一个字符串,它可以被视为数组(索引下标)但永远不会被视为字典(键下标)。
  • @vadian,那我该怎么办?我没有太多编程经验。
  • 您在代码中打印了 dataDescription,您能否将结果包含在内?
  • 首先,这可能不是您想要使用 .map 的方式。其次,不清楚你实际上想要做什么。最后,我们不知道 document 中有什么。您能否解释一下您要完成的工作,并说明您的 Firestore 文档结构是什么样的?
  • @JoakimDanielson,我从 Firebase Firestore 文档中获得了这一切并编辑了我的帖子。

标签: swift firebase google-cloud-firestore


【解决方案1】:

让我通过一个例子来解决这个问题。假设您有一个带有用户集合的 FireStore,并且每个文档都有一个用户 uid 的 documentID,并将他们的名称存储在一个字段中。它看起来像这样

users
   uid_1
      name: "Henry"

我们想要访问该用户的姓名字段。这是读取该文档、打印 uid 和名称的代码。

func readUsersName() {
    let users = self.db.collection("users")
    let thisUser = users.document("uid_1")
    thisUser.getDocument { documentSnapshot, error in
        if let error = error {
            print(error.localizedDescription)
            return
        }

        let docId = documentSnapshot?.documentID
        let name = documentSnapshot?.get("name") as! String
        print(docId, name)
    }
}

【讨论】:

  • swift 的文档实际上是这样说的: docRef.getDocument { (document, error) in if let document = document, document.exists { let dataDescription = document.data().map(String.初始化(描述:))?? "nil" print("Document data: (dataDescription)") } else { print("Document does not exist") } },但你写的东西说有效。我没有使用 .get("name"),我认为这就是原因。
  • @Something 如果您查看我上面对您的问题的评论,具体问题是 您已添加 profilename?.text 并且它不是正确的地方。。其余代码都很好并且与文档匹配,但该行不适用于字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多