0
struct Record {
    let title: String
    let date: Date
}

let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())!


let record1 = Record(title: "Visit 1", date: today)
let record2 = Record(title: "Visit 2", date: yesterday)
let record3 = Record(title: "Visit 3", date: tomorrow)

// array of structs

let records = [record1, record2, record3]

I have an array of records. I want to get an array of all of the record's date properties so I can sort them.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Have a look at the higher order functions of arrays `filter` and `map` and a combination / one of these might get you to your solution – Shawn Frank Mar 23 '22 at 16:32
  • Is this really what you want, isn’t it better to sort the array directly using the `date` property? Like in [this question](https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – Joakim Danielson Mar 23 '22 at 17:10
  • If you just want an array of dates, use map: `let dates: [Date] = records.map {$0.date}` – Duncan C Mar 23 '22 at 17:25
  • 1
    @DuncanC better to use keypath in this case `let dates = records.map(\.date)` – Leo Dabus Mar 23 '22 at 18:16
  • Good point Leo. I still haven't trained myself to use that syntax yet, and revert to old habits. – Duncan C Mar 23 '22 at 18:42

0 Answers0