如何基于数组swift对多个数组进行排序?

时间:2016-03-02 03:24:42

标签: ios arrays swift sorting nsdate

我想基于一个NSDate数组

的数组对多个数组进行排序
var date = [NSDate]()
var name = [String]()
var job = [String]()

我想根据日期对姓名和工作进行排序。例如

date = [2016-04-02 01:03:42 +00002,2016-03-02 01:03:42 +0000,2016-05-02 01:03:42 +0000] 

name = [john,alex,danson]

job = [engineer,programmer,swimmer]

我想将日期从最旧到最新排序然后我想根据日期对名称和工作进行排序。结果将像

date = [2016-03-02 01:03:42 +0000 ,2016-04-02 01:03:42 +0000 , 2016-05-02 01:03:42 +0000 ] //Being Sorted
name = [alex,john,danson]
job = [programmer,engineer,swimmer]

我该怎么做?

2 个答案:

答案 0 :(得分:0)

extension NSDate {
    var day: Int { return NSCalendar.currentCalendar().components(.Day, fromDate: self).day }
}

let result = zip(zip(date, name), jobs).map { ($0.0.0, $0.0.1, $0.1) }.sort { $0.0.day < $1.0.day }
print(result)

这应该这样做。如果您需要解释,我会尝试解释。

如果您希望对现有阵列进行排序:

name = name.enumerate().sort { date[$0.index].day < date[$1.index].day }.map { $0.element }
jobs = jobs.enumerate().sort { date[$0.index].day < date[$1.index].day }.map { $0.element }

但是,这样做并不安全,因为如果namejobs的大小大于date,则会崩溃。在使用它之前,你必须在内部构建一些安全措施。

我忘了提到的是,你也可以得到原作&#34;通过从result中提取数组进行排序:

name = result.map { $0.1 }
jobs = result.map { $0.2 }

答案 1 :(得分:0)

这是一个编程问题,而不是Swift问题。

let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let dateStrings = ["2016-03-02 01:04:42 +0000","2016-04-02 01:03:42 +0000" , "2016-05-02 01:03:42 +0000" ]
let date = dateStrings.map {
    dateString in formatter.dateFromString(dateString)}
let name = ["alex","john","danson"]
let job = ["programmer","engineer","swimmer"]

let combine = date.enumerate().map {
    index, date in
    return (date!,name[index],job[index])
    }

let result = combine.sort{
    $0.0.compare($1.0) == NSComparisonResult.OrderedDescending
}