user5855868 user5855868 - 2 months ago 14
Swift Question

Unique array of objects

I have an array that looks like this:

var persons = [Person]()


And a person contains this:

id : Int
name : String
age : Int
gender : String


In my persons list I have multiple persons, but how do I sort this list on unique names?

I found this
let unique = Array(Set(originals))
but it does not seem to work on a list of objects, I want to keep all the information of the object.

If my list contains these rows:

Adam, Adam, John, John, Michael, Nick, Tony


I only want to show:

Adam, John, Michael, Nick Tony


And I still want to be able to get Adams age for example.

Any ideas?

Edit

Person declaration

import Foundation

public class Person : NSObject {
var id = ""
var name = ""
var age = 0
var gender = ""
}

func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}

Answer

You need to add this extension to return an ordered set from your people array.

extension Array where Element: Equatable {
    var orderedSetValue: Array {
        return reduce([]){ $0.contains($1) ? $0 : $0 + [$1] }
    } 
}

You will also have to make your Person class Equatable:

func ==(lhs: Person, rhs: Person) -> Bool {
    return lhs.id == rhs.id
} 

class Person: Equatable { 
    let id: String 
    let name: String 
    init(id: String, name: String) { 
        self.id = id 
        self.name = name 
    } 
}

Testing

let person1 = Person(id: "1", name: "Adam") 
let person2 = Person(id: "1", name: "Adam") 
let person3 = Person(id: "2", name: "John") 
let person4 = Person(id: "2", name: "John") 
let person5 = Person(id: "3", name: "Michael") 
let person6 = Person(id: "4", name: "Nick") 
let person7 = Person(id: "5", name: "Tony") 
let people = [person1,person2,person3,person4,person5,person6,person7] 
people.orderedSetValue //[{id "1", name "Adam"}, {id "2", name "John"}, {id "3", name "Michael"}, {id "4", name "Nick"}, {id "5", name "Tony"}]
Comments