ios - Empty return value from swift function containing closure -
i created function should return dictionary filled data retrieved (using json, based on ray wenderlich tut) online. code in closure. problem empty dictionary returned first, , afterwards gets filled. don't know if related delay in getting remote data, need dictionary filled first before returning it. here code.
func getstatusfromremotesource() -> [statusmodel] { var statusupdates = [statusmodel]() println("statusupdates after initialization: \(statusupdates)") // 1 datamanager.getstatusdatawithsuccess { (statusdata) -> void in let json = json(data: statusdata) if let jsonarray = json.array { jsonitem in jsonarray { var statusversion: string? = jsonitem["version"].string var statusdescription: string? = jsonitem["message"].string var statuscode: int? = jsonitem["code"].string!.toint() var update = statusmodel(version: statusversion, message: statusdescription, code: statuscode) statusupdates.append(update) println("statusupdates after appending update: \(statusupdates)") // 3 (after other function call) } let item = 0 println("version \(statusupdates[item].version) has status \(statusupdates[item].message)") // println("status code: \(statusupdates[item].code)") } } println("status updates before return: \(statusupdates)") // 2 return statusupdates }
so //1
prints first, //2
(still empty) , other function (that calls one) called. //3
printed (correctly) content should retrieved.
how can fill statusupdates
dictionary before returning it?
you should use closures in method return statusupdates async method. empty statusupdates returned in code when using closures, can wait till datamanager.getstatusdatawithsuccess finished:
typealias remotestatushandler = (status:[statusmodel]) -> void func getstatusfromremotesource(handler:remotestatushandler){ var statusupdates = [statusmodel]() println("statusupdates after initialization: \(statusupdates)") // 1 datamanager.getstatusdatawithsuccess { (statusdata) -> void in let json = json(data: statusdata) if let jsonarray = json.array { jsonitem in jsonarray { var statusversion: string? = jsonitem["version"].string var statusdescription: string? = jsonitem["message"].string var statuscode: int? = jsonitem["code"].string!.toint() var update = statusmodel(version: statusversion, message: statusdescription, code: statuscode) statusupdates.append(update) println("statusupdates after appending update: \(statusupdates)") // 3 (after other function call) } let item = 0 println("version \(statusupdates[item].version) has status \(statusupdates[item].message)") // println("status code: \(statusupdates[item].code)") } handler(status: statusupdates) } }
then function can called this:
getstatusfromremotesource { (status) -> void in //use status here, function void. }
Comments
Post a Comment