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

Time:02-18

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 {

    }
}

CodePudding user response:

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! }
  • Related