I\'ve read many articles on SO and I\'m still stumped! I have an array of dictionaries, see below:
var myArray = [[String:AnyObject]]()
myArray.append([
To sort by caseNumber
:
myArray.sortInPlace { ($0["caseNumber"] as! String) < ($1["caseNumber"] as! String) }
Note, this uses caseNumber
as a String
which could lead to surprising results (for example "12345" < "2"
). You might either want to store caseNumber
as an Int
, or convert it to an Int
when sorting:
myArray.sortInPlace { Int($0["caseNumber"] as! String) < Int($1["caseNumber"] as! String) }
To sort by caseLUD
:
myArray.sortInPlace { ($0["caseLUD"] as! NSDate).compare($1["caseLUD"] as! NSDate) == .OrderedAscending}
.OrderedAscending
will give you earliest date first, and .OrderedDescending
will give you latest date first.
If you stored your data in a Struct
instead of a Dictionary
, you could avoid the messy typecasting.
struct CaseRecord {
var caseNumber: Int
var formType: String
var caseStatus: String
var caseDetails: String
var caseLUD: NSDate
var friendlyName: String
}
var myArray = [CaseRecord]()
myArray.append(CaseRecord(
caseNumber : 12345,
formType : "Advanced",
caseStatus : "Approved",
caseDetails : "blah blah",
caseLUD : NSDate(),
friendlyName : "name1"
)
)
myArray.append(CaseRecord(
caseNumber : 124,
formType : "Standard",
caseStatus : "On-Hold",
caseDetails : "blah blah",
caseLUD : NSDate(),
friendlyName : "name2"
)
)
myArray.append(CaseRecord(
caseNumber : 13,
formType : "Normal",
caseStatus : "Rejected",
caseDetails : "blah blah",
caseLUD : NSDate(),
friendlyName : "name3"
)
)
myArray.sortInPlace { $0.caseNumber < $1.caseNumber }
myArray.sortInPlace { $0.caseLUD.compare($1.caseLUD) == .OrderedDescending }