简体   繁体   English

Swift:从Swift 2转换为Swift 3失败

[英]Swift: Conversion from Swift 2 to Swift 3 Failing

I have been at this now for a few days. 我现在已经来这几天了。
I am simply trying to convert my project from Swift 2 to Swift 3, and I have fixed quite a few errors. 我只是想将我的项目从Swift 2转换为Swift 3,并且已经修复了很多错误。
However, I am down to the last 19, all of which are the same error. 但是,我到了最后19个,所有这些都是相同的错误。
Basically, I have a request to a server that returns a JSON object. 基本上,我有一个对返回JSON对象的服务器的请求。
That JSON object has nested objects in side of it. 该JSON对象在其侧面具有嵌套对象。
I have been Googling and reading for multiple hours trying different things and unfortunately, nothing has worked. 我一直在谷歌搜索和阅读多个小时,尝试各种不同的方法,但不幸的是,没有任何效果。
Any help is appreciated. 任何帮助表示赞赏。
(Note: I have been asked on previous questions to post what I have already tried. (注意:有人问我以前的问题,以发布我已经尝试过的内容。
I am not going to do that here because I have tried many different ways to fix this issue) 我不会在这里这样做,因为我尝试了许多不同的方法来解决此问题)

Error: Type 'Any' has no subscript members 错误:类型“ Any”没有下标成员

if let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
    if let data = response["data"] as? NSArray {
        for (index, item) in data.enumerated() {
            let id = item["id"] as! String
        }
    }
}

Here are a few things I have tried: 这是我尝试过的一些方法:

if let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
    if let data = response["data"] as? NSArray {
        for (index, item):[String:AnyObject] in data.enumerated() {
            let id = item["id"] as! String
        }
    }
}

if let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
    if let data = response["data"] as? NSArray {
        for (index, item) in data.enumerated() as? NSArray {
            let id = item["id"] as! String
        }
    }
}

if let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
    if let data = response["data"] as? NSArray {
        for item in data as? NSArray {
            let id = item["id"] as! String
        }
    }
}

None of the above fixed the issue. 以上都不解决此问题。 Here are the SOF questions I have referenced: 以下是我引用的SOF问题:

  1. type any? 输入任何? has no subscript members 没有下标成员
  2. Facebook SDK error for subscript members 下标成员的Facebook SDK错误
  3. Type 'Any' has no subscript members (firebase) 类型“任何”没有下标成员(firebase)
  4. Type 'Any' Has no Subscript Members in xcode 8 Swift 3 类型'Any'在xcode 8 Swift 3中没有下标成员
  5. Type 'Any' has no subscript members after updating to Swift 3 更新为Swift 3后,类型'Any'没有下标成员

Any help is greatly appreciated! 任何帮助是极大的赞赏!

Hello You can try this: 您好,您可以尝试以下操作:

if let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
    if let data = response["data"] as? [AnyObject] {
        for (index, item) {
           if let id = item["id"] as! String{
               print(id)
            }
        }
    }
}

or 要么

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary              

  if let parseJson = json {              
   if let data = parseJson["data"] as? [AnyObject] {                   
     for signleArray in data  {                  
          if let customObjects = signleArray as? [AnyObject] {                  
             for customObject in customObjects {                  
                let userId = customObject["id"] as! String
               }
             }
           }
         }
       }

Just let me know how it worked, so we can figure it out :) 请让我知道它是如何工作的,以便我们找出来:)

Alright, so after some help from 0ndre_, here is how I fixed the problem. 好的,因此在获得0ndre_的帮助后,这是我解决问题的方法。 Unfortunately, it wasn't a complete fix for multidimensional / nested objects so I had to modify my API that the application is calling. 不幸的是,它不能完全解决多维/嵌套对象,因此我不得不修改应用程序正在调用的API。

if let response = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
    if let data = response["data"] as? [AnyObject] {
        for (index, item) in data.enumerated() {
            let id = item["id"] as! String
        }
    }
}

You should not cast to NSArray , but [AnyObject] . 您不应该转换为NSArray ,而应该转换为[AnyObject] When enumerating an NSArray , in Swift 3 that id item type maps to Any , which indeed doesn't have a subscript. 在枚举NSArray ,在Swift 3中, id项类型映射为Any ,而实际上没有下标。 You'll find more info on Any vs AnyObject in the standard library documentation , and the rationale for this Swift 3 change for treating id as Any vs AnyObject is explained in this Swift evolution proposal . 您可以在标准库文档中找到有关Any vs AnyObject更多信息,此Swift 3 提案中对此Swift 3更改将id视为Any vs AnyObject进行了说明。

      let inputData:Data = "{\"data\": [{\"id\":\"x\"},{\"id\":\"y\"},{\"id\":\"z\"}]}".data(using: .utf8)!

      if let response = try JSONSerialization.jsonObject(with: inputData, options: []) as? [String:AnyObject],
      let responseData = response["data"] as? [AnyObject]
      {
          for (index, item) in responseData.enumerated()
          {
              let id = item["id"] as! String
              print(id)
          }
      }

Regarding using 3rd party libraries such as SwiftyJSON for JSON parsing, you may not like 3rd party modules, but your code above will crash on bad input (if item doesn't have key "id" or if it's not a string). 关于使用第三方库(例如SwiftyJSON)进行JSON解析,您可能不喜欢第三方模块,但是上面的代码将在错误输入时崩溃(如果item没有键“ id”或不是字符串)。 It's of course not like libraries like SwiftyJSON or Freddy are the only way to write robust JSON parsing code in Swift, but the Cocoa provided facilities certainly are not using the Swift type system to the benefit of the programmer and it's easy to be complacent to bad input with that API, the more complex the parsing task (which in all likelihood shouldn't really crash your program, but should be reported as an error). 当然,这不是像SwiftyJSON或Freddy这样的库是在Swift中编写健壮的JSON解析代码的唯一方法,但是Cocoa提供的工具肯定不是在使用Swift类型系统,这对程序员没有好处,而且很容易沾沾自喜使用该API输入,解析任务就更加复杂(很可能不会真正使程序崩溃,而应该将其报告为错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM