user11700369
user11700369

Reputation:

Get the dictionary object in array that has the lowest value in Swift

I have an array of dictionaries as follows:

    (
        {
        daysToExpiration = 3;
    },
        {
        daysToExpiration = 87;
    },
        {
        daysToExpiration = 24;
    }
)

I would like to retrieve the dictionary with the smallest value for the key daysToExpiration. In the above example, the dictionary that should be retrieved would be at index 0 (3 < 24 < 87).

What I have tried: looping through the array and getting the value for the key, setting that value to a constant, and then comparing the next value from the loop to that constant and determining if it is higher/lower.

Is there a simpler way to achieve this in Swift? What is the most efficient way to handle this situation?

Upvotes: 0

Views: 707

Answers (1)

Alexander
Alexander

Reputation: 63321

Use Array.min(by:).

let nextToWidgetToExpire = widgets.min(by: { $0.daysToExpiration })

Upvotes: 2

Related Questions