0

I have three date objects. I want to know, which of them is the oldest. I found a lot about how to compare two dates, but not multiple...

So I have my three date variables:

var firstDate:Date!
var secondDate:Date!
var thridDate:Date!

and I assign dates to them:

firstDaten = dateOne
secondDate = dateTwo
thridDate = dateThree

How can I find out in Swift, which of my dates is the oldest?

Tanks for help!

2
  • 1
    Maybe you should delete your previous question? [firstDate, secondDate, thridDate].sorted().prefix(1) Commented Nov 14, 2020 at 18:34
  • irie, implicit in vadian's answer below, finding the earliest date and sorting dates are two different things. Use min if you just want the earliest date. Only use sorted if you really need all of the dates sorted. Sorting the full array is more computationally expensive than just identifying the smallest value (though, admittedly, when dealing with so few records, it's not likely to result in observable performance difference). So, sort if you need to, but grab min if that's really all you care about. Commented Nov 14, 2020 at 19:37

1 Answer 1

3

As Date conforms to Comparable, create an array and use the min() function

let dates = [firstDate, secondDate, thridDate]
let oldest = dates.min()

Note:

It is not necessary to declare a variable as implicit unwrapped optional if a value is assigned right after the declaration, this compiles:

let firstDate : Date
firstDate = dateOne
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.