samedi 27 juin 2015

A best practice for multithreading within a function that returns a value, Swift

I have a question that might be not specifically about implementation but rather a tip/best practice thing.

I am working on a class in Swift that gets data from an online source in JSON format. I want to have specific methods in this class that connect to the online source and give the result back in a Dictionary type. The function might be like this:

func getListFromOnline()->[String:String]{

    var resultList : [String:String]=[:]
    ...
    /*
    Some HTTP request is sent to the online source with NSURLRequest

    Then I parse the result and assign it to the resultList
    */
    ...

    return resultList
}

What I get right now in this implementation, without the multithreading, the resultList is apparently returned before fetching from the online source is done. Not surprisingly, it leads to failure in the program.

Any idea or tip how I can achieve the opposite? I am a bit confused with multithreading in this instance, because I want to call this public method asynchronously later from another class and I know how to do that, but I don't get how to make the method that returns an argument have multithreading within itself.

Or is it not about multithreading at all and I am not seeing an obvious solution here?

Aucun commentaire:

Enregistrer un commentaire