Find the right value in an Array, or in an Array of Dictionaries

From time to time I discover a new way of coding something that significantly improves readability & minimizes how much I need to code. 

Here’s one of such latest discoveries. Typically to find a value in an array (or in an array of dictionaries) with a specific condition I would do a for loop with an if statement checking for the right value. This works great of course, but its a lot of code to do something that simple. 

Here’s a simple way to find a value in an array of dictionaries:

let matchingArticle = arrayOfItems.first(where: {$0.exampleKey == 3843})

 

We ask the arrayOfItems to give us the first value where the dictionary key exampleKey takes the value 3843. 

And if it’s only an array of int or string, for example, is even easier:

 let matchingArticle = arrayOfItems.first(where: {$0 == 859})

We simply ask the arrayOfItems to give us the first value where the its value equals 859. 

Note, in this code example we assume you will always have only up to 1 match. 

I’ve come to love this function and I think you will too. 

 

Questions / comments / suggestions? I’m at @MarcMasVi 

Marc