0

Dispatching the queue messes up the order in the array as noted below. I'm trying to rank the array and then be able to translate it. So far its not working:

 let top5 = Array(labels.sorted{ $0.confidence > $1.confidence}.prefix(upTo:5))


 for lulu in top5 {

    let translator = ROGoogleTranslate()

    var params = ROGoogleTranslateParams()
    params.source = "en"
    params.target = "es"
    params.text = "\(String(describing: lulu.label))"

    translator.translate(params: params, callback: { (result) in

        DispatchQueue.main.async {

            self.textUno.text = self.textUno.text! + "\(lulu.label)" + "  \(lulu.confidence*100)\n"
            self.textDos.text = self.textDos.text!  + "\(result)\n"

            self.view.addSubview(self.textUno)
            self.view.addSubview(self.textDos)
        }
    })                    
}

If I try to put the sorting out of DispatchQueue.main.async then the translation won't be lined up with the right word.

How can I fix this so that the array is sorted and the translation matches up ?

1 Answers1

1

Translate the array first before ranking them.

Make it simpler first and make sure it is working and then put all the parts together.

If you really want to do it this way you will need to put them into a temporary array after sorting them and then use that at the end.

This, as you said, will return a jumbled result.

The below example is pretty close, needs a bit of a polish but you should be able to do it from this.

  let top5 = Array(labels.sorted{ $0.confidence > $1.confidence}.prefix(upTo:5))
var tmparr : []
var count: Int = 0 
 for lulu in top5 {

    let translator = ROGoogleTranslate()
     count = count + 1
    var params = ROGoogleTranslateParams()
    params.source = "en"
    params.target = "es"
    params.text = "\(String(describing: lulu.label))"
    params.ordernumber = count 
    translator.translate(params: params, callback: { (result) in
        tmparr.append[params]
   })

}

DispatchQueue.main.async {

 for lulunew in tmparr {
 if (lulunew.ordernumber == correctindex){


            self.textUno.text = self.textUno.text! + "\(lulu.label)" + "  \(lulu.confidence*100)\n"
            self.textDos.text = self.textDos.text!  + "\(result)\n"

            self.view.addSubview(self.textUno)
            self.view.addSubview(self.textDos)
 }
}
        }
Kingsley Mitchell
  • 2,412
  • 2
  • 18
  • 25