Sorting an array of dictionaries in Swift 2

后端 未结 1 2021
北海茫月
北海茫月 2021-01-14 09:11

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([
            


        
相关标签:
1条回答
  • 2021-01-14 09:33

    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 }
    
    0 讨论(0)
提交回复
热议问题