Collect a number of unique property values ​​in an array of Swift objects


Say I have a simple Ingredient class:

class Ingredient {
    let section : String // 'Produce', 'Spices', 'Dairy', 'Grains'

And I have a pile of Ingredient items:

var ingredients : [Ingredient] = ...

I want to collect the number of distinct sections from these ingredients.

I can do this in Java via (relying on the auto-clumping of Set types):

Or, using the distinct() method:

But I'm looking for a way to do a similar one-liner in Swift. Some of the research I've done shows people writing their own methods to collect distinct values, but I was hoping there would be a distinct() or Set-collecting method for Swift types.

Sure, you can do this in much the same way by mapping over your ingredients array to extract an array of sections – you can then convert these to a Set and get out the count, giving you the number of distinct sections.

let distinctSections = Set({$0.section}).count