Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get max date (Future) from an object array swift

This is my object, where I want to get the highest expiresDate.

struct LatestReceiptInfo {
    var productId: String?
    var expiresDate: Date? = nil
    var isInIntroOffer_period: Bool?
    var isTrialPeriod: Bool?
    var cancellationDate: Date? = nil
}

latestReceiptInfoArray is my array.

for latestReceiptInfo in latestReceiptInfoArray {
    //2. Get the highest expire_date from latestInfoReceiptObjects array
    if let exDate = latestReceiptInfo.expiresDate {

    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you’re only looking for the date, instead of the LatestReceiptInfo with the highest date, than you could compactMap the dates (takes out nil-values) and then get the highest one with the max function.

let highestDate = latestReceiptInfoArray
    .compactMap { $0.expiresDate }
    .max()

If you want to get the LatestReceiptInfo with the highest date, various approaches will do the trick. For instance by filtering all values that actually have a date. After that you can force-unwrap (yugh) the date in the comparison.

let highestReceiptInfo = latestReceiptInfoArray
    .filter { $0.expiresDate != nil }
    .max { $0.expiresDate! < $1.expiresDate! }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading