我有一个NSMutableArray(比如->
)。数组的内容是Model(比如accountListArray
,其属性为BankAccountModel
)。
现在我想根据默认属性对accountListArray的内容进行排序,即defaultAcc - Y/N
all account that is defaultAcc enabled (Y) should be on top.
怎么做?
答案 0 :(得分:1)
试试这个:
创建模型属性,如下所示
class BankAccountModel: NSObject {
static let sharedInstance: BankAccountModel = BankAccountModel()
var isDefault: Bool = false
// assign value
if let objDefault = dictionary["default"] {
isDefault = (objDefault as! String) == "Y" ? true : false
}
// var default = "" // Y or N
}
排序如下
self.arrOfModels.sort {
return $0.isDefault && !$1.isDefault // isSelected is your flag . you need to change with your flag
}
或
另一个字符串
的解决方案self.arrModels.sort {
return ($0. defaultAcc == "Y") && ($1. defaultAcc == "N")
}
答案 1 :(得分:1)
这是我的例子。它将对数组进行排序,在排序后,名称为2的人和名称为4的人将位于数组的顶部
class People{
var name = ""
var isMale:Bool = false
init(name:String,isMale:Bool){
self.name = name
self.isMale = isMale
}
}
var person1 = People(name: "1",isMale: false)
var person2 = People(name: "2",isMale: true)
var person3 = People(name: "3",isMale: false)
var person4 = People(name: "4",isMale: true)
var array = [person1,person2,person3,person4]
array.sort() { Int(NSNumber(value:($0.isMale))) > Int(NSNumber(value:($1.isMale))) }
答案 2 :(得分:1)
除上述答案外。您可以将模型定义为Comparable,然后实现自己的>,<,==协议:
例如:
class BankAccountModel: Comparable { //or struct
var accountHolder: String = ""
var balance: Decimal?
var enabled: Bool = false
init(holder: String, balance: Decimal, enabled: Bool) {
self.accountHolder = holder
self.balance = balance
self.enabled = enabled
}
static func == (lhs: BankAccountModel, rhs: BankAccountModel) -> Bool {
return lhs.enabled == rhs.enabled
}
static func > (lhs: BankAccountModel, rhs: BankAccountModel) -> Bool {
return lhs.enabled || (!lhs.enabled && !rhs.enabled)
}
static func < (lhs: BankAccountModel, rhs: BankAccountModel) -> Bool {
return rhs.enabled || (!rhs.enabled && !lhs.enabled)
}
}
let account1 = BankAccountModel(holder: "Holder 1", balance: Decimal(10.0), enabled: true)
let account2 = BankAccountModel(holder: "Holder 2", balance: Decimal(20.3), enabled: false)
let account3 = BankAccountModel(holder: "Holder 3", balance: Decimal(-1.0), enabled: false)
let account4 = BankAccountModel(holder: "Holder 4", balance: Decimal(0.0), enabled: true)
var allAccounts = [account1, account2, account3, account4]
allAccounts.sort(by: {return $0 > $1})
答案 3 :(得分:1)
Swift 3.0
希望对你有用。
let sortedArr = accountListArray.sorted(by: {
let item1 = $0 as! BankAccountModel
let item2 = $1 as! BankAccountModel
if item1.defaultAcc > item2.defaultAcc {
return true
}
return false
})