类型 'Any' 没有下标成员 [英] type 'Any' has no subscript members

查看:12
本文介绍了类型 'Any' 没有下标成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let employerName = snapshot.value! ["employerName"] as! String
let employerImage = snapshot.value! ["employerImage"] as! String
let uid = snapshot.value! ["uid"] as! String

我查看了以前的帖子,但似乎找不到解决此问题的方法.所有三行代码都给出了类型'Any'没有下标成员"的错误.对此相当陌生,因此非常感谢您的帮助.

I reviewed previous posts but cannot seem to find a way to solve this problem. All three lines of code give the "type 'Any' has no subscript members" error. Fairly new to this so any help is appreciated.

推荐答案

snapshot.value 的类型为 Any.下标是一种特殊的函数,它使用将值括在大括号中的语法.这个下标函数由Dictionary实现.

snapshot.value has a type of Any. A subscript is a special kind of function that uses the syntax of enclosing a value in braces. This subscript function is implemented by Dictionary.

所以这里发生的事情是,作为开发人员的您知道 snapshot.value 是一个 Dictionary,但编译器不知道.它不会让你调用 subscript 函数,因为你试图在 Any 类型的值上调用它,而 Any 没有实现 <代码>下标.为此,您必须告诉编译器您的 snapshot.value 实际上是一个 Dictionary.此外,Dictionary 允许您使用带有 Dictionary 键的任何类型值的下标函数.所以你需要告诉它你有一个 Dictionary 键为 String(AKA [String: Any]).更进一步,在您的情况下,您似乎知道 Dictionary 中的所有值也是 String,所以不要在下标后转换每个值使用 as! 将其转换为 StringString,如果你只是告诉它你的 Dictionary 有两个 String 类型的键和值(AKA [String: String]),那么您就可以通过下标来访问这些值,并且编译器也会知道这些值也是 String

So what is happening here is that YOU as the developer know that snapshot.value is a Dictionary, but the compiler doesn't. It won't let you call the subscript function because you are trying to call it on a value of type Any and Any does not implement subscript. In order to do this, you have to tell the compiler that your snapshot.value is actually a Dictionary. Further more Dictionary lets you use the subscript function with values of whatever type the Dictionary's keys are. So you need to tell it you have a Dictionary with keys as String(AKA [String: Any]). Going even further than that, in your case, you seem to know that all of the values in your Dictionary are String as well, so instead of casting each value after you subscript it to String using as! String, if you just tell it that your Dictionary has keys and values that are both String types (AKA [String: String]), then you will be able to subscript to access the values and the compiler will know the values are String also!

guard let snapshotDict = snapshot.value as? [String: String] else {
    // Do something to handle the error 
    // if your snapshot.value isn't the type you thought it was going to be. 
}

let employerName = snapshotDict["employerName"]
let employerImage = snapshotDict["employerImage"]
let uid = snapshotDict["fid"]

这就给你了!

这篇关于类型 'Any' 没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆