Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/110.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 按日期数组排列的Swift地图数组_Ios_Swift_Swift3 - Fatal编程技术网

Ios 按日期数组排列的Swift地图数组

Ios 按日期数组排列的Swift地图数组,ios,swift,swift3,Ios,Swift,Swift3,我正在努力做到这一点:[ 但我必须按NSDate数组排序 // dates are actual NSDates, I pasted strings into my sample var dates:[NSDate] = [2019-12-20 13:00 +0000, 2019-12-20 13:00 +0000, 2019-12-12 13:00 +0000] var people:[String] = ["Harry", "Jerry", "Hannah"] var peopleIds:[

我正在努力做到这一点:[ 但我必须按NSDate数组排序

// dates are actual NSDates, I pasted strings into my sample
var dates:[NSDate] = [2019-12-20 13:00 +0000, 2019-12-20 13:00 +0000, 2019-12-12 13:00 +0000]
var people:[String] = ["Harry", "Jerry", "Hannah"]
var peopleIds:[Int] = [1, 2, 3, 4]


// the following line doesn't work.
// i tried a few variations with enumerated instead of enumerate and sorted instead of sort
// but with now luck
let sortedOrder = dates.enumerate().sort({$0.1>$1.1}).map({$0.0})

dates = sortedOrder.map({points[$0]})
people = sortedOrder.map({people[$0]})
peopleIds = sortedOrder.map({peopleIds[$0]})

将日期声明从
NSDate
更改为
Date
Date
符合自Swift 3.0以来的
可比
协议。这样做,您只需对日期进行排序
dates.sorted(by:>)
。要将数组排序在一起,您可以压缩数组,按日期排序并映射排序后的元素:

let sortedZip = zip(dates, zip(people, peopleIds)).sorted { $0.0 > $1.0}
let sortedPeople = sortedZip.map{ $0.1.0 }
let sortedIDs = sortedZip.map{ $0.1.1 }

如果您试图对相关字段进行排序,您应该真正考虑使用某种模型使用面向对象的方法,然而,以下应该达到您所要做的:

var n=min(dates.count、people.count、peopleid.count)
var tuples=(0..$1.0作为日期}
dates=tuples.map{$0.0}
people=tuples.map{$0.1}
peopleId=tuples.map{$0.2}

日期
符合自Swift 3.0以来的
可比
协议。因此,您可以简单地对日期进行排序
日期。排序(按:>)
Hi Leo.Thanx我刚试过,但是得到了这个警告:二进制运算符'>'不能应用于两个'NSDate'操作数。如果没有其他方法,我想我可以尝试添加一个额外的数组来将日期转换为纯数字。@MartinVidic在每个日期之后添加
作为日期
,所以
{$0.0作为日期>$1.0作为日期}
@MartinVidic将日期声明从
NSDate
更改为
Date
。您应仅使用Swift nativeclasses@LeoDabus
NSDate
直接连接到
Date
,反之亦然。如果OP坚持使用NSDate,一个简单的cast也可以解决这个问题,一个更好的方法是使其符合比较也能