Swift 按日期数组映射数组
Swift Map ARRAYS by Date Array
我正在尝试完成此任务:[
但我必须按 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({[=11=].1>.1}).map({[=11=].0})
dates = sortedOrder.map({points[[=11=]]})
people = sortedOrder.map({people[[=11=]]})
peopleIds = sortedOrder.map({peopleIds[[=11=]]})
将您的日期声明从 NSDate
更改为 Date
。 Date
自 Swift 3.0 起符合 Comparable
协议。这样做您可以简单地对日期进行排序 dates.sorted(by: >)
。要将数组排序在一起,您可以压缩数组,按日期排序并映射排序的元素:
let sortedZip = zip(dates, zip(people, peopleIds)).sorted { [=10=].0 > .0}
let sortedPeople = sortedZip.map{ [=10=].1.0 }
let sortedIDs = sortedZip.map{ [=10=].1.1 }
如果您正在尝试对关联字段进行排序,您应该真正考虑使用某种模型的面向对象方法,但是,以下方法应该可以实现您正在尝试做的事情:
var n = min(dates.count, people.count, peopleIds.count)
var tuples = (0 ..< n).map { (dates[[=10=]], people[[=10=]], peopleIds[[=10=]]) }
.sorted { [=10=].0 as Date > .0 as Date }
dates = tuples.map{ [=10=].0 }
people = tuples.map{ [=10=].1 }
peopleIds = tuples.map{ [=10=].2 }
我正在尝试完成此任务:[
// 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({[=11=].1>.1}).map({[=11=].0})
dates = sortedOrder.map({points[[=11=]]})
people = sortedOrder.map({people[[=11=]]})
peopleIds = sortedOrder.map({peopleIds[[=11=]]})
将您的日期声明从 NSDate
更改为 Date
。 Date
自 Swift 3.0 起符合 Comparable
协议。这样做您可以简单地对日期进行排序 dates.sorted(by: >)
。要将数组排序在一起,您可以压缩数组,按日期排序并映射排序的元素:
let sortedZip = zip(dates, zip(people, peopleIds)).sorted { [=10=].0 > .0}
let sortedPeople = sortedZip.map{ [=10=].1.0 }
let sortedIDs = sortedZip.map{ [=10=].1.1 }
如果您正在尝试对关联字段进行排序,您应该真正考虑使用某种模型的面向对象方法,但是,以下方法应该可以实现您正在尝试做的事情:
var n = min(dates.count, people.count, peopleIds.count)
var tuples = (0 ..< n).map { (dates[[=10=]], people[[=10=]], peopleIds[[=10=]]) }
.sorted { [=10=].0 as Date > .0 as Date }
dates = tuples.map{ [=10=].0 }
people = tuples.map{ [=10=].1 }
peopleIds = tuples.map{ [=10=].2 }