类型“任何"没有下标成员 [英] type 'Any' has no subscript members
问题描述
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
没有实现subscript
.为此,您必须告诉编译器您的snapshot.value
实际上是Dictionary
.另外,Dictionary
允许您将下标函数与Dictionary
的键的任何类型的值一起使用.因此,您需要告诉它您有一个Dictionary
,其键为String
(也称为[String: Any]
).更进一步,在您的情况下,您似乎知道Dictionary
中的所有值也都是String
,因此,在使用as! String
将每个值下标到String
之后,不要将每个值都强制转换为,如果仅告诉您Dictionary
具有同时为String
类型的键和值(也称为[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"]
就在那里!
这篇关于类型“任何"没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!