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
  }
}
0

2 Answers 2

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 }
Sign up to request clarification or add additional context in comments.

Comments

0

you should write the following code.

  • for descending

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

  • for ascending

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

1 Comment

Thanks a lot, mates. Could not imagine that a one-liner can do so much:-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.