Type Any 没有下标成员

Type Any has no subscript members

我发现很难将完成回调中的结果传递到我的 ViewController 中进行访问。我可以在执行 for 循环时打印我的对象,但我无法访问对象内的特定值。

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

在我的ViewController

    getMedia(){success in
        for item in success{
            print(item["image"]) //This causes error
            print(item) //This prints the object perfectly
        }
    }

问题正是错误消息告诉您的:要下标变量,需要将其声明为支持下标的类型,但您已将数组声明为包含 AnyAny 作为最基本的类型,不支持下标。

假设您的数组包含字典,请改为这样声明您的 getMedia 函数:

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

或者,如果字典可能包含非字符串键:

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

如果字典中的值都具有相同的类型,请根据需要将 Any 替换为该类型。