1

I try to append json data that I got from my server to array of object and want to remove any duplicate if there is any

this is my custom class

class datastruct {

    var id: Int?
    var name: String?

    init(add: NSDictionary) {
        id = add["id"] as? Int
        name = add["name"] as? String
    }
}

and this is my code that I use to append json to my array

    var data:Array< datastruct > = Array < datastruct >()
    Alamofire.request(url)
                .responseJSON{ response in
                    switch response.result {
                    case .success(let JSON):
                        if let list = JSON as? NSArray {
                            for i in 0 ..< list.count {
                                if let res = list[i] as? NSDictionary {
                                    self.data.append(datastruct(add: res))
                                }
                            }
                            self.refresh()
                        }

                    case .failure(let error):

                    }

                }

the problem is I already search several solution to remove any duplicate array in stackoverflow

Remove duplicate objects in an array

Remove duplicates from array of objects

Removing Duplicates From Array of Custom Objects Swift

but I when I try to use Hashable I don't know where to put Set to my code because it is NSDictionary

Please help me how to remove duplicate of array or give me some hint

Community
  • 1
  • 1
Dirus
  • 1,033
  • 2
  • 14
  • 21

1 Answers1

5

I think it is easier way to solve this problem. First your datastruct class should be extend NSObject. Then Add isEqual(_ object: Any?) method in your datastruct. like this way.

class datastruct : NSObject {

    var id: Int?
    var name: String?

    init(add: NSDictionary) {
        id = add["id"] as? Int
        name = add["name"] as? String
    }

    override func isEqual(_ object: Any?) -> Bool {
        let obj = object as! datastruct
        if self.id == obj.id {
            return true
        } else {
            return false
        }
    }   
}

Now you can check for duplication.

if let res = list[i] as? NSDictionary {
    let dataStructObj =  datastruct(add: res)
    if !data.contains(dataStructObj) {
        self.data.append(dataStructObj)
    }

}

I hope it will help you.

jignesh Vadadoriya
  • 3,244
  • 3
  • 18
  • 29