SWIFT 2 - Sort Multi dimensional array by date

戏子无情 提交于 2019-12-25 03:34:56

问题


I am trying to sort my array by date, I have been trying almost everything but with no results.

This is the closer I got but I get a waring:

Constant 'sortedDate' inferred to have type ()

var Names = [[String]]()

 Names = [
            ["aaa", "bob", "ccc", "26-10-2015 17:50"],
            ["aaa-1", "bbb-1", "ccc-1", "22-10-2015 11:20"],
            ["aaa-2", "bbb-2", "bbb-2", "01-03-2015 17:00"]
        ]

let sortedDate = Names.sortInPlace({ return $0[3].compare($1[3]) == NSComparisonResult.OrderedAscending })

        print("\(sortedDate)")

回答1:


Your data is String, not date. Use an NSDateFormatter to convert it to NSDate:

let names = [
    ["aaa", "bob", "ccc", "26-10-2015 17:50"],
    ["aaa-1", "bbb-1", "ccc-1", "22-10-2015 11:20"],
    ["aaa-2", "bbb-2", "bbb-2", "01-03-2015 17:00"]
]

let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm"

let sortedDate = names.sort {
    let date1 = formatter.dateFromString($0[3])
    let date2 = formatter.dateFromString($1[3])
    return date1?.timeIntervalSince1970 < date2?.timeIntervalSince1970
}


来源:https://stackoverflow.com/questions/33357568/swift-2-sort-multi-dimensional-array-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!