Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 无法为类型为';字符串';索引类型为';字符串';快速错误_Swift_Firebase_Google Cloud Firestore - Fatal编程技术网

Swift 无法为类型为';字符串';索引类型为';字符串';快速错误

Swift 无法为类型为';字符串';索引类型为';字符串';快速错误,swift,firebase,google-cloud-firestore,Swift,Firebase,Google Cloud Firestore,首先,其他问题和我的不一样在从Firebase Firestore检索数据后,我试图从Swift Xcode中的数据中获取单个值。相反,它给出了一个错误: 无法用“String”类型的索引为“String”类型的值下标 错误发生在 profilename?.text = dataDescription["name"] as! String 线路 dataDescription的打印格式为: 缓存的文档数据:[“电子邮件”:test2@gmail.com,“名称”:Test2,“电话”:408-

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

无法用“String”类型的索引为“String”类型的值下标

错误发生在

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

dataDescription的打印格式为:

缓存的文档数据:[“电子邮件”:test2@gmail.com,“名称”:Test2,“电话”:408-222-2222]


有人能帮我吗?

让我通过一个例子来回答这个问题。假设您有一个带有用户集合的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)
    }
}

错误明确指出,
dataDescription
是一个字符串,可以作为数组(下标索引)处理,但不能作为字典(下标键)。@vadian,那么我该怎么办?我没有太多编程经验。如果在代码中打印dataDescription,是否可以包含结果?首先,这可能不是您希望使用.map的方式。其次,不清楚你到底想做什么。最后,我们不知道文档中有什么。你能解释一下你试图完成的任务并包括你的Firestore文档结构吗?@JoakimDanielson,我从Firebase Firestore文档中得到了这些,并编辑了我的帖子。swift的文档实际上是这样写的:docRef.getDocument{(文档,错误)在if let document=document,document.exists{let dataDescription=document.data().map(String.init(description:)?“nil”print(“document data:(dataDescription)”)}或者{print(“document不存在”)}中,但您所写的都是有效的。我没有使用.get(“name”),我想这就是为什么。@如果你看我上面对你的问题的评论,具体的问题是你添加了profilename?.text,它不是正确的位置。。代码的其余部分很好,并且与文档匹配,但该行对于字符串不起作用。
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)
    }
}