ios 在 xcode 8 Swift 3 中键入“Any”没有下标成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39516199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:09:52  来源:igfitidea点击:

Type 'Any' Has no Subscript Members in xcode 8 Swift 3

iosjsonswiftswift3xcode8

提问by DaVinci1223

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

我的应用程序应该转到特定位置以下拉它需要加载的网站。在 2.3 中它就像一个魅力,但自从我更新了 xcode(我没有很多经验)它给了我错误“类型'Any'没有下标成员”并突出显示“json”就在第三行之前

...Retriever = json["WEB"]...

this is the code related to it.

这是与之相关的代码。

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)

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

我觉得我错过了一些小事。如果有更好的方法来做到这一点,我希望得到建议。URL 返回此 JSON

{
  "WEB" : [
           {
            "URL" : "http://www.google.com"
           }    
          ]
}

but I would love it if I could simplify it to just

但如果我能把它简化成这样,我会很喜欢的

{"URL":"http://www.google.com"}

回答by Bista

Try this:

尝试这个:

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

Safe way:

安全方式:

do {
    if let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String:Any] {
        print(json)
    }
} catch let err{
    print(err.localizedDescription)
}

You have to cast type Anyto Swift dictionary type [String:AnyObject].

您必须将 type 转换Any为 Swift 字典 type [String:AnyObject]

Edit: Swift 3
In swift 3 the purpose of AnyObjectis more clarified. So more favourable Swift Dictionary type will be [String:Any].

编辑:Swift 3
Swift 3 中,目的AnyObject更加明确。所以更有利的 Swift 字典类型将是[String:Any].

Anyis an alias for any data type.
AnyObjectis an alias for any data type derived from a class.

Any是任何数据类型的别名。
AnyObject是从类派生的任何数据类型的别名。

For more info visit: https://craiggrummitt.com/2016/09/16/any-vs-anyobject-vs-nsobject-in-swift-3/

欲了解更多信息,请访问:https: //craiggrummitt.com/2016/09/16/any-vs-anyobject-vs-nsobject-in-swift-3/