[英]Type '[String:Any]' has no subscript members in Swift
I am trying to get information from a json result and append and access certain key values. 我试图从json结果中获取信息,并追加和访问某些键值。 However, I am getting the error "Type '[String:Any]' has no subscript members.
但是,我收到错误消息“类型'[String:Any]'没有下标成员。
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
for case let studentsInfo in json["results"] {
if let studentInfo = StudentResults(json: result) {
let name = firstName + " " + lastName
StudentsResults.append(name)
}
This is also the struct that I have placed in an extension. 这也是我放置在扩展中的结构。
struct StudentResults{
let firstName: String
let lastName: String
let latitude: Double
let longitude: Double
let mapString:String
let mediaURL: String
let objectID:String
let uniqueKey: String
let updatedAt: String
}
convenience init?(json: [String: Any]) {
guard let firstName = json["firstName"] as? String,
let lastName = json["lastName"] as? String
else {
return nil
}
return nil
This is also my GitHub page for this project if you would like to take a look at it 如果您想看看这个项目,这也是我的GitHub页面
https://github.com/SteveBurgos95/UdacityMapProject https://github.com/SteveBurgos95/UdacityMapProject
It appears to me that the problem is with this line of code: 在我看来,问题出在这行代码上:
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
Whilst you are force casting it here as! [String: Any]
当您强制将其投射
as! [String: Any]
as! [String: Any]
, the try?
as! [String: Any]
, try?
is giving you an optional value. 给您一个可选的值。
You have two options. 您有两个选择。 You can be a crazy person and change
try?
您可以成为一个疯狂的人并
try?
改变try?
to try!
try!
, or you can take the safer approach and wrap the code like so: ,或者您可以采用更安全的方法并像下面那样包装代码:
do {
guard let json = try JSONSerialization.jsonObject(with: data!, options: []) as [String: Any] else { return }
…
} catch {
// HANDLE ERROR
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.