Empty return value from swift function containing closure

后端 未结 1 1890
长情又很酷
长情又很酷 2021-01-26 15:18

I created a function that should return a dictionary filled with data that are retrieved (using json, based on Ray Wenderlich tut) online. That code is in a closure. The problem

相关标签:
1条回答
  • 2021-01-26 16:05

    You should use Closures in method to return statusUpdates as its Async method. The empty statusUpdates will be returned immediately in your code but when using closures, you can wait till DataManager.getStatusDataWithSuccess is 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 {
    
            for 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 your function can be called like this:

    getStatusFromRemoteSource { (status) -> Void in
       //use status here, this function is void.
    }
    
    0 讨论(0)
提交回复
热议问题