2017-02-09 85 views
0

请问能否告诉我如何根据“currentPoints”值对“bonusCardsArray”中的多个“BonusCard”数组进行排序(降序,升序)。Swift 3 sort jsonArray

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

回答

1

排序到位(升序w.r.t.到currentPoints属性),使用的sort(by:) method

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

或者,创建一个新的阵列;原来的排序版本,利用sorted(by:) method

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

你应该写下面的代码。

  • 降序

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

  • 为升序

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

+0

非常感谢,伙伴们。无法想象一个单线可以做这么多:-) – Jim