TheAbstractDev
TheAbstractDev

Reputation: 159

Return value on a closure Swift

I'm working on a project and I have to replace a String on my xmlFile with a string who contains the subtitles language separated by commas.

The problem is that I'm getting my subtitles with a closure function and I can't return values but I have to store in a variable my subtitles.

Here is an example of my code

func searchSubtitles(completion: ([String] -> Void)) {
   // GET Request for subtitles
   // ....
   completion(["fr", "en", "it", "es"])
}

func getSubtitles(completion:(String -> Void)) {
  var subs = ""
  searchSubtitles { (data) in
    for i in 0 ..< data.count {
      subs.appendContentsOf(data[i])
      subs.appendContentsOf(", ")
    }
  }
}

var SubStr: String {
  // have to return the string who contains all subtitles
}

// ...

myXMLFile = myXMLFile.stringByReplacingOccurrencesOfString("{{SUBS}}", withString: SubStr)
// Adding subs to my file

Upvotes: 1

Views: 872

Answers (2)

D4ttatraya
D4ttatraya

Reputation: 3404

I think you can use semaphore for this problem as:

func getSubtitles() -> String {
  let sem = DispatchSemaphore(value: 0)
  var subs = ""
  searchSubtitles { (data) in
    for i in 0 ..< data.count {
      subs.appendContentsOf(data[i])
      subs.appendContentsOf(", ")
    }
    sem.signal()
  }
  sem.wait(timeout: .distantFuture)
  return subs
}

var SubStr: String {
  // have to return the string who contains all subtitles
  return getSubtitles()
}

Upvotes: 0

LiMar
LiMar

Reputation: 2952

Given that you work with API based on asynchronous completion you will have a difficulty of working procedurally (when functions return values and then you call other functions).

Callbacks (completion handler) model suggests using return values from within completion handler.

In other words - you may want to move your myXMLFile.stringByReplacingOccurrencesOfString() call INTO getSubtitles() completion handler.

Upvotes: 1

Related Questions