简体   繁体   English

需要帮助按 Swift 中的时间戳对结构进行排序

[英]Need help sorting a Struct by Timestamp in Swift

Trying to sort a Swift struct by timestamp and really need some help.尝试按时间戳对 Swift 结构进行排序,并且确实需要一些帮助。 My struct definition is as follows:我的结构定义如下:

struct TripDetails {

  let tripDepartureTime: String
  var myLocations: [GeoPoint]
  var myDates: [Timestamp]

}

And in the variable todaysTrip is the following data:在变量 todaysTrip 中是以下数据:

TripDetails(
tripDepartureTime: "2020-05-23 22:56:52 +0000", 

myLocations: [<FIRGeoPoint: (21.561333, -80.033536)>, 
<FIRGeoPoint: (22.561288, -80.023592)>, 
<FIRGeoPoint: (20.561265, -80.063439)>], 

myDates: [<FIRTimestamp: seconds=1590274922 nanoseconds=795317000>, 
<FIRTimestamp: seconds=1590274802 nanoseconds=683353000>, 
<FIRTimestamp: seconds=1590274682 nanoseconds=679319000>])

I want to sort all the fields of the particular trip based on the times of the myDates timestamp in descending order.我想根据 myDates 时间戳的时间按降序对特定行程的所有字段进行排序。 Been at it for awhile and can't figure out what I'm doing wrong.做了一段时间,无法弄清楚我做错了什么。 I've seen several posts here on StackOverflow dealing with this question but none of them seem to work in my case.我在 StackOverflow 上看到了几篇关于这个问题的帖子,但它们似乎都不适用于我的情况。

Suggest you to change structure of your model:建议您更改 model 的结构:

struct TripDetails {
    struct LocationInfo {
        var location: GeoPoint
        var timestamp: TimeStamp
    }

    let tripDepartureTime: String
    var locations: [LocationInfo]

} 

Sorting:排序:

var tripDetails = ... // Getting model
tripDetails.locations.sort(by: { $0.timestamp.seconds > $1.timestamp.seconds })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM