1

please can you tell me how to sort (descending, ascending) multiple arrays of "BonusCard" in "bonusCardsArray" on the basis of its "currentPoints" values.

//Array to sort according to "currentPoints" 
var bonusCardsArray = [BonusCard]()

//basis class
class BonusCard {

  var companyName             : String
  var bonusCardDescription    : String
  var currentPoints           : Int
  var bonusCardType           : Int


  init(companyName: String, bonusCardDescription: String,    
  currentPoints: Int, bonusCardType: Int) {

      self.companyName = companyName
      self.bonusCardDescription = bonusCardDescription
      self.currentPoints = currentPoints
      self.bonusCardType = bonusCardType
  }
}
Jim
  • 13
  • 4

2 Answers2

2

To sort in place (ascending order w.r.t. to the currentPoints property), make use of the sort(by:) method

bonusCardsArray.sort { $0.currentPoints < $1.currentPoints }

Or, to create a new array; the sorted version of the original one, make use of the sorted(by:) method

let sortedfBonusCardsArray = bonusCardsArray
    .sorted { $0.currentPoints < $1.currentPoints }
dfrib
  • 70,367
  • 12
  • 127
  • 192
0

you should write the following code.

  • for descending

    bonusCardsArray.sorted({ $0. currentPoints > $1. currentPoints })

  • for ascending

    bonusCardsArray.sorted({ $0. currentPoints < $1. currentPoints })

Nikunj Damani
  • 753
  • 3
  • 11