Type 'Any' has no subscript members error in swift 4

I haveπŸ‘‡

Type 'Any' has no subscript members

error in :point_down:
self.imageList = jsonDictionary["imageList"] as! [String]

line

this is my all code :point_down::point_down:

 let session = URLSession.shared
    let url = URL(string: "http://onlinegallery.local/")
    let task = session.dataTask(with: url!) { (data, response, error) in
        do{
            let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
            self.imageList = jsonDictionary["imageList"] as! [String]
        }catch{
            print("Error")
        }
        
        
    }
    task.resume()

You need to do:

let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]

Alternatively you could model the JSON as a Codable structure and use the JSONDecoder.

import Foundation

struct Gallery: Codable {
    var imageList: [String]
}

func test(data: Data) throws -> [String] {
    let gallery = try JSONDecoder().decode(Gallery.self, from: data)
    return gallery.imageList
}

// A simple test for the above.

let json = """
    {
        "imageList": [
            "Hello.png",
            "Cruel.png",
            "World.png"
        ]
    }
    """
let jsonData = json.data(using: .utf8)!
print(try! test(data: jsonData))
// -> ["Hello.png", "Cruel.png", "World.png"]

Share and Enjoy

Quinn β€œThe Eskimo!” @ DTS @ Apple

Terms of Service

Privacy Policy

Cookie Policy