在我的应用程序中,我使用AlamofireObjectMapper。 我想做一个返回对象数组的方法。在Alamofire的帮助下,我做了一个GET请求,它将响应作为responseArray。 使用void函数数组listOfType
始终有值。 但是当我使用非void函数应该返回对象数组MedicineType
,数组listOfType
为零。 所以这里是我的代码。返回Alamofire对象数组
func getAll() -> [MedicineType] {
var listOfTypes: [MedicineType]?;
Alamofire.request(BASE_URL, method:.get)
.responseArray(keyPath:"value") {(response: DataResponse<[MedicineType]>) in
if let status = response.response?.statusCode {
switch(status) {
case 200:
guard response.result.isSuccess else {
//error handling
return
}
listOfTypes = response.result.value;
default:
log.error("Error", status);
}
}
}
return listOfTypes!;
}
你需要这样做的关闭,而不是回报,因为你的呼吁Alamofire是异步所以你的反应将是异步 –
看为“Swift + Closure + Async”。如果仔细检查,'listOfTypes!;'应该被调用BEFORE'listOfTypes = response.result.value;'(你可以添加打印) – Larme