Search code examples
iosswiftsetequatable

How do I create a Set of custom objects (Swift)?


For my iOS app I have a model something like

class Person {
    var Id: Int
    var Name: String

    init(id: Int, name: String?) {
        self.Id = id
        self.Name = name ?? ""
    }
}

Then later on in my ViewController when I load data from the server I add some people to an array

class ViewController: UIViewController {
    var people:[Person] = []

    override func viewDidLoad() {
        self.loadPeople()
    }

    func loadPeople() {
        // This data will be coming from a server request
        // so is just sample. It could have users which 
        // already exist in the people array

        self.people.append(Person(id: "1", name: "Josh"))
        self.people.append(Person(id: "2", name: "Ben"))
        self.people.append(Person(id: "3", name: "Adam"))
    }
}

What I am now trying todo is turn the people array into a Set<Person> so it will not add duplicates. Is this possible to do or do I need to change my logic?


Solution

  • To make set of Person you need to make it conform to Equatable and Hashable protocols:

    class Person: Equatable, Hashable {
        var Id: Int
        var Name: String
    
        init(id: Int, name: String?) {
            self.Id = id
            self.Name = name ?? ""
        }
    
        var hashValue: Int {
            get {
                return Id.hashValue << 15 + Name.hashValue
            }
        }
    }
    
    func ==(lhs: Person, rhs: Person) -> Bool {
        return lhs.Id == rhs.Id && lhs.Name == rhs.Name
    }
    

    Then you can use set of persons like this:

    var set = Set<Person>()
    set.insert(Person(id: 1, name: "name"))