-2

I'm finding it very difficult to pass my result in my completion callback to access in my ViewController. I can print my object when I do my for loop but I cant access specific values inside the object.

public func getMedia(completion: @escaping (Array<Any>) -> ()){
    Alamofire.request(URL(string: MEDIA_URL)!,
        method: .get)
        .responseJSON(completionHandler: {(response) -> Void in
            if let value = response.result.value{
                let json = JSON(value).arrayValue
                completion(json)
            }
        }
    )
}

In my ViewController

    getMedia(){success in
        for item in success{
            print(item["image"]) //This causes error
            print(item) //This prints the object perfectly
        }
    }
Thomas Charlesworth
  • 1,789
  • 5
  • 28
  • 53

1 Answers1

0

The problem is exactly what the error message is telling you: to subscript a variable, it needs to be declared as a type which supports subscripting, but you've declared your array as containing Any. And Any, being the most basic type there is, doesn't support subscripting.

Assuming your array contains dictionaries, declare your getMedia function like this instead:

public func getMedia(completion: @escaping ([[String : Any]]) -> ())

Or, if there's a chance that the dictionary might contain non-string keys:

public func getMedia(completion: @escaping ([[AnyHashable : Any]]) -> ())

If the values in the dictionary all have the same type, replace Any with that type as appropriate.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60