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

1
  • conform your class Datastruct with Equatable protocol. look SO for more info. Commented Feb 22, 2017 at 4:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.