在xcode 8 Swift 3中输入'Any'没有下标成员 [英] Type 'Any' Has no Subscript Members in xcode 8 Swift 3
问题描述
我的应用程序应该转到特定位置来下载需要加载的网站。在2.3它的工作就像一个魅力,但因为我已经更新了xcode(我没有很多经验)它给我错误类型'任何'没有下标成员并突出显示json就在第三行之前
My App is supposed to go to a specific location to pull down the website it needs to load. In 2.3 it worked like a charm, but since I've updated xcode (which I don't have a ton of experience in) it is giving me the error "type 'Any' has no subscript members" and highlighting the "json" right before line three
...Retriever = json["WEB"]...
这是与之相关的代码。
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)
if let Retriever = json["WEB"] as? [[String: AnyObject]] {
for website in Retriever {
if let name = website["URL"] as? String {
self.loadAddressURL(name)
我觉得我是错过了一些小事。如果有更好的方法,我会喜欢建议。该URL返回此JSON
I feel like I am missing something small. If there is a better way to do this, I would love suggestions. The URL returns this JSON
{
"WEB" : [
{
"URL" : "http://www.google.com"
}
]
}
但我很乐意,如果我可以将其简化为
but I would love it if I could simplify it to just
{"URL":"http://www.google.com"}
推荐答案
试试这个:
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
安全方式:
do {
if let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String:Any] {
print(json)
}
} catch let err{
print(err.localizedDescription)
}
你必须将类型任何
转换为Swift字典类型 [String:AnyObject]
。
You have to cast type Any
to Swift dictionary type [String:AnyObject]
.
编辑:Swift 3
在swift中3更清楚了 AnyObject
的目的。所以更有利的Swift Dictionary类型将是 [String:Any]
。
Swift 3
In swift 3 the purpose of AnyObject
is more clarified. So more favourable Swift Dictionary type will be [String:Any]
.
任何
是任何数据类型的别名。
AnyObject
是从类派生的任何数据类型的别名。
Any
is an alias for any data type.
AnyObject
is an alias for any data type derived from a class.
有关详细信息,请访问: https://craiggrummitt.com/2016/09/16/any-vs-anyobject-vs-nsobject -in-swift-3 /
For more info visit: https://craiggrummitt.com/2016/09/16/any-vs-anyobject-vs-nsobject-in-swift-3/
这篇关于在xcode 8 Swift 3中输入'Any'没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!