arraysswiftdistinct-values

get distinct elements in an array by object property


I have an array of object. I want to get distinct elements in this array by comparing objects based on its name property

class Item {
var name: String
init(name: String) {
    self.name = name
}
}
let items = [Item(name:"1"), Item(name:"2"), Item(name:"1"), Item(name:"1"),Item(name:"3"), Item(name:"4")]

result:

let items = [Item(name:"1"), Item(name:"2"),Item(name:"3"), Item(name:"4")]

how can I do this in swift?


Solution

  • Hope this will help you:

    class Item:Equatable, Hashable {
        var name: String
        init(name: String) {
            self.name = name
        }
        var hashValue: Int{
          return name.hashValue
        }
    
    }
    
    func ==(lhs: Item, rhs: Item) -> Bool {
        return lhs.name == rhs.name
    }
    
    
    let items = [Item(name:"1"), Item(name:"2"), Item(name:"1"), Item(name:"1"),Item(name:"3"), Item(name:"4")]
    
    var uniqueArray = Array(Set(items))