Craig Otis Craig Otis - 6 months ago 15
Swift Question

Collect number of unique property values in Swift array of 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):

ingredients.stream().map(Ingredient::getSection).collect(Collectors.toSet()).count()


Or, using the
distinct()
method:

ingredients.stream().map(Ingredient::getSection).distinct().count()


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.

Answer

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(ingredients.map{$0.section}).count