2017-02-09 43 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