gpt4 book ai didi

swift - Alamofire responseArray keyPath 的字符串数组

转载 作者:行者123 更新时间:2023-11-28 15:21:06 25 4
gpt4 key购买 nike

我有一个 rest 调用,它返回 keyPath“数据”的字符串 [String] 数组,例如......

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

我正在尝试通过 responseArray(keyPath: "data") 获取它, 但在 *.responseArray(keyPath: "data") {(response: DataResponse<[String]>) in* 行出现编译错误

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

部分请求示例

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

你们有人知道怎么做吗?

最佳答案

问题是字符串不可映射。根据 https://github.com/Hearst-DD/ObjectMapper/issues/487 ,这些是建议的解决方案:

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


使用 Swift 的 4 Codable(无外部依赖):

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

关于swift - Alamofire responseArray keyPath 的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com