Search code examples
swiftalamofireobjectmapper

Alamofire responseArray String array for keyPath


I have a rest call which returns array of string [String] for keyPath "data", for example...

{
  "data": [
    "1",
    "3",
    "5",
    "2",
    "4",
    "9"
  ]
}

I am trying to get it via responseArray(keyPath: "data"), but get compile error for line *.responseArray(keyPath: "data") {(response: DataResponse<[String]>) in*

Cannot convert value of type '(DataResponse<[String]>) -> ()' to expected argument type '(DataResponse<[_]>) -> Void'

Part of request example

alamofireManager.request(url)
        .responseArray(keyPath: "data") {(response: DataResponse<[String]>) in
        if response.result.isSuccess {
           if let data = response.result.value {
                //process success
            } else {
                // handle error
            }
        }
        ...

Does anybody of you know how to do it ?


Solution

  • The problem is that String isn't Mappable. As per https://github.com/Hearst-DD/ObjectMapper/issues/487, these are the proposed solutions:

    In this situation I would recommend accessing the data directly from the Alamofire response. You should be able to simply cast it to [String].

    Alternatively, you may be able to subclass String and make the subclass Mappable, however I think that is more work than necessary for the your situation


    Using Swift's 4 Codable (no external dependencies):

    struct APIResponse: Decodable {
        let data: [String]
    }
    
    let url = "https://api.myjson.com/bins/1cm14l"
    Alamofire.request(url).responseData { (response) in
    
        if response.result.isSuccess {
            if let jsonData = response.result.value,
                let values = try? JSONDecoder().decode(APIResponse.self, from: jsonData).data {
                //process success
                print(values)
            } else {
                // handle error
            }
        }
    }