iosswiftxcodesortingnscoding

Sorted Array/Map Swift


I performed a GET request, and I saved data inside data like this

if let data: [MyMap] = response?.results {
   let var_to_sort = data
   self.generateStuff(var: var_to_sort)
}

MyMap is a mappable object defined like this:

class MyMap: NSCoding {
   var name: String?
   var score: Score?
   ...

With mapping, encode etc ... Score is the same as the one above:

class Score:NSCoding {
   var number: Double?
   ...

What I need is to sort var_to_sort = data based on number (from greatest to leasts) and pass it to the generateStuff method. Remember that response.results has more than 1 object. Someone can help me?


Solution

  • Simply sort your array:

    let var_to_sort = data.sorted {
      $0.score?.number ?? 0 > $1.score?.number ?? 0
    }