1

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
}
14
  • You need to make your class Person Equatable and then you can use this extension stackoverflow.com/questions/25738817/… Commented Sep 5, 2016 at 4:24
  • @LeoDabus, I have done that now but I´m not sure how to filter the list now. Commented Sep 5, 2016 at 4:30
  • func ==(lhs: Person, rhs: Person) -> Bool { return lhs.id == rhs.id } Commented Sep 5, 2016 at 4:30
  • Just use yourArray.orderedSetValue Commented Sep 5, 2016 at 4:31
  • What does sorting on unique names mean? Does it mean taking out duplicate records and then sorting on name field? Commented Sep 5, 2016 at 4:37

1 Answer 1

2

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

extension Collection where Element: Hashable {
    var orderedSet: [Element] {
        var set: Set<Element> = []
        return reduce(into: []){ set.insert($1).inserted ? $0.append($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.orderedSet //[{id "1", name "Adam"}, {id "2", name "John"}, {id "3", name "Michael"}, {id "4", name "Nick"}, {id "5", name "Tony"}]
Sign up to request clarification or add additional context in comments.

2 Comments

He has added you on Skype now Leo, have you seen it?
I will check it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.