anonymous anonymous - 1 month ago 5
Swift Question

Compare objects and edit array

I want to create array of unique elements by specific property.


I have array of objects (Person) :

struct Person {
var name: String?
var secondName: String?

init (name: String, secondName: String) { = name
self.secondName = secondName

let person1 = Person(name: "name1", secondName: "secondName1")
let person2 = Person(name: "name2", secondName: "secondName2")
let person3 = Person(name: "name1", secondName: "secondName3")

let personsArray = [person1, person2, person3]

I want to get new array, that will contain person objects with unique name

something like this $ == $

What is the best way to achieve that ?

Result should be arrays of objects with unique name param = [[person1, person3], [person2]]


This is my personal interpretation of your question

Given an array of Person(s) you want in output several dictionaries where the key is the name of a person and the value is a list of persons with that name.

Here's the code

let dict = persons.reduce([String:[Person]]()) { (dict, person) -> [String:[Person]] in
    var dict = dict
    dict[] = (dict[] ?? []) + [person]
    return dict