Swift 3排序jsonArray

时间:2017-02-09 10:35:24

标签: arrays json swift sorting

请您告诉我如何根据其“currentPoints”值对“bonusCardsArray”中的多个“BonusCard”数组进行排序(降序,升序)。

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

2 个答案:

答案 0 :(得分:2)

要进行排序(将w.r.t.升级到currentPoints属性),请使用sort(by:) method

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

或者,创建一个新数组;原始版本的排序版本,使用sorted(by:) method

let sortedfBonusCardsArray = bonusCardsArray
    .sorted { $0.currentPoints < $1.currentPoints }

答案 1 :(得分:0)

你应该写下面的代码。

  • 降序

    bonusCardsArray.sorted({$ 0.currentPoints&gt; $ 1.currentPoints})

  • 升序

    bonusCardsArray.sorted({$ 0.currentPoints&lt; $ 1.currentPoints})