我具有请求功能,并且在获取JSON之后。我将数据解析为结构实例。我如何从函数中返回该实例?现在它返回的是nil变量。
获取JSON并将其解析为结构正常运行,返回实例时出现问题。
class FinantialRequest {
static func getData(id: Int, year: Int, mod : String, period: String)->CinemaChartModel{
let parameters: Parameters = [
"idc": id,
"yy": year,
"func": mod
]
var chartModelSample = CinemaChartModel()
request("https://placeholder.com/app.php", method: .post, parameters: parameters, encoding: URLEncoding.default).debugLog().responseJSON { responseJSON in
switch responseJSON.result {
case .success(let value):
do {
let parsedData = try FirebaseDecoder().decode(FinDataSample.self, from: value)
parsedData.data.forEach { sample in
switch sample.b.name {
case "Оборот кино":
switch finantialDataSample.period! {
case "1 Квартал":
chartModelSample.moneyPeriodCinema = sample.k1
chartModelSample.moneyBudgetPeriodCinema = sample.b.k1
case "2 Квартал":
chartModelSample.moneyPeriodCinema = sample.k2
chartModelSample.moneyBudgetPeriodCinema = sample.b.k2
case "3 Квартал":
chartModelSample.moneyPeriodCinema = sample.k3
chartModelSample.moneyBudgetPeriodCinema = sample.b.k3
case "4 Квартал":
chartModelSample.moneyPeriodCinema = sample.k4
chartModelSample.moneyBudgetPeriodCinema = sample.b.k4
default: break
}
chartModelSample.moneyYyCinema = sample.yy
chartModelSample.moneyBudgetYyCinema = sample.b.yy
case "Количество людей":
switch finantialDataSample.period! {
case "1 Квартал":
chartModelSample.peoplePeriodCinema = sample.k1
chartModelSample.peopleBudgetPeriodCinema = sample.b.k1
case "2 Квартал":
chartModelSample.peoplePeriodCinema = sample.k2
chartModelSample.peopleBudgetPeriodCinema = sample.b.k2
case "3 Квартал":
chartModelSample.peoplePeriodCinema = sample.k3
chartModelSample.peopleBudgetPeriodCinema = sample.b.k3
case "4 Квартал":
chartModelSample.peoplePeriodCinema = sample.k4
chartModelSample.peopleBudgetPeriodCinema = sample.b.k4
default: break
}
chartModelSample.peopleYyCinema = sample.yy
chartModelSample.peopleBudgetYyCinema = sample.b.yy
default:
break
}
}
} catch let error {
print(error)
}
case .failure(let error):
print(error)
}
}
return chartModelSample
}
答案 0 :(得分:0)
由于请求方法本身是关闭,因此您不能直接从中返回。您需要这样的完成处理程序:
static func getData(id: Int, year: Int, mod : String, period: String, completion: ((CinemaChartModel?)->Void)){
.............
}
并使用如下结构触发它:
completion(chartModelSample)
或者如果没有返回值,则可以使用nil值触发它
completion(nil)
您可以这样调用此方法:
getData(id: Int, year: Int, mod : String, period: String, completion:{ (model) -> Void in
.......
})