recoilnetworks recoilnetworks - 2 months ago 24
iOS Question

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.
However, I am down to the last 19, all of which are the same error.
Basically, I have a request to a server that returns a JSON object.
That JSON object has nested objects in side of it.
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

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:


  1. type any? has no subscript members

  2. type any? has no subscript members in swift 3

  3. Type 'Any' has no subscript members (firebase)

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

  5. Type 'Any' has no subscript members after updating to Swift 3



Any help is greatly appreciated!

Answer

Alright, so after some help from 0ndre_, here is how I fixed the problem. Unfortunately, it wasn't a complete fix for multidimensional / nested objects so I had to modify my API that the application is calling.

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
        }
    }
}