Removing Duplicates From Array of Custom Objects Swift
You can do it with a set of strings, like this:
var seen = Set<String>()
var unique = [DisplayMessage]
for message in messagesWithDuplicates {
if !seen.contains(message.id!) {
unique.append(message)
seen.insert(message.id!)
}
}
The idea is to keep a set of all IDs that we've seen so far, go through all items in a loop, and add ones the IDs of which we have not seen.
Swift removing duplicate from array of object
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.
Remove objects with duplicate properties from Swift array
I am going to suggest 2 solutions.
Both approaches will need Post
to be Hashable
and Equatable
Conforming Post to Hashable and Equatable
Here I am assuming your Post
struct (or class) has an id
property of type String
.
struct Post: Hashable, Equatable {
let id: String
var hashValue: Int { get { return id.hashValue } }
}
func ==(left:Post, right:Post) -> Bool {
return left.id == right.id
}
Solution 1 (losing the original order)
To remove duplicated you can use a Set
let uniquePosts = Array(Set(posts))
Solution 2 (preserving the order)
var alreadyThere = Set<Post>()
let uniquePosts = posts.flatMap { (post) -> Post? in
guard !alreadyThere.contains(post) else { return nil }
alreadyThere.insert(post)
return post
}
How to remove duplicate elements from an array in Swift 5?
Most efficient way if you don’t care about maintaining the original order in the array
let uniqueUsers = Array(Set(users))
How to merge two custom type arrays and remove duplicate custom type items in Swift?
I have resolved this issue based on @Hamish 's comment and the link .
class Obj: NSObject {
var va1: String? = nil
var va2: Int? = nil
var value : Int
init(_ v1: String,_ v2: Int){
va1 = v1
va2 = v2
super.init()
}
override var hashValue : Int {
var hashValueString = va1 ?? ""
hashValueString += "\(va2 ?? 0)"
return hashValueString.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
if let other = object as? Obj {
return self.hashValue == other.hashValue
} else {
return false
}
}
}
var objArray1: [Obj] = [Obj("a", 1), Obj("b", 2), Obj("c", 3)]
var objArray2: [Obj] = [Obj("a", 1), Obj("b", 2), Obj("d", 4)]
objArray1 += objArray2
var objSet = Array(Set(objArray1))
Removing duplicate elements from an array in Swift
You can roll your own, e.g. like this:
func unique<S : Sequence, T : Hashable>(source: S) -> [T] where S.Iterator.Element == T {
var buffer = [T]()
var added = Set<T>()
for elem in source {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
let vals = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
let uniqueVals = uniq(vals) // [1, 4, 2, 6, 24, 15, 60]
And as an extension for Array
:
extension Array where Element: Hashable {
func uniqued() -> Array {
var buffer = Array()
var added = Set<Element>()
for elem in self {
if !added.contains(elem) {
buffer.append(elem)
added.insert(elem)
}
}
return buffer
}
}
Or more elegantly (Swift 4/5):
extension Sequence where Element: Hashable {
func uniqued() -> [Element] {
var set = Set<Element>()
return filter { set.insert($0).inserted }
}
}
Which would be used:
[1,2,4,2,1].uniqued() // => [1,2,4]
Remove duplicate elements in swift array of objects
Classes of type NSObject will automatically call isEqual() for the contains() method. You can override the superclass's implementation to fit your logic.
If your class HAS to inherit NSObject, then use:
class Event: NSObject {
var key: String?
init(key: String) {
self.key = key
}
override func isEqual(_ object: Any?) -> Bool {
guard let event = object as? Event else { return false }
return self.key == event.key
}
}
var event = Event(key: "abc")
var eventCopy = Event(key: "abc")
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
return reduce(into: []) { result, element in
if !result.contains(element) {
result.append(element)
}
}
}
}
var events = [event, eventCopy]
events = events.removeDuplicates()
print(events.count)
If your class does not inherit NSObject, make it conform to the Equatable protocol.
class Event: Equatable {
var key: String?
init(key: String) {
self.key = key
}
static func ==(lhs: Event, rhs: Event) -> Bool {
return lhs.key == rhs.key
}
}
var event = Event(key: "abc")
var eventCopy = Event(key: "abc")
extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
var result = [Element]()
for value in self {
if result.contains(value) == false {
result.append(value)
}
}
return result
}
}
var events = [event, eventCopy]
events = events.removeDuplicates()
print(events.count)
remove duplicates from struct
You can filter this way after you finish appending to the array.
var unique = [WheelBrand]()
for arrValue in itemWheelBrand {
if !unique.contains(where: { $0.id == arrValue.id }) {
unique.append(arrValue)
}
}
Related Topics
Xcode: "This App Could Not Be Installed at This Time."
Moving the Cursor to the Beginning of Uitextfield
Save and Load from Keychain | Swift
How to Switch to Different Storyboard for iPhone 5
Distancefromlocation - Calculate Distance Between Two Points
Cannot Set Searchbar as Firstresponder
How to Hide Status Bar in Uiimagepickercontroller
Decimal to Fraction Conversion in Swift
How to Create a Hex Color String Uicolor Initializer in Swift
How to Change Uidatepicker to a Specific Time (In Code)
How to Install iOS 7 and Onwards Simulators in Xcode 7 Beta 5
Clear Background for Form Sections in Swiftui
Uibezierpath Triangle with Rounded Edges
Warning: the Copy Bundle Resources Build Phase Contains This Target's Info.Plist File
How to Turn the iPhone Camera Flash On/Off
Uicollectionview Header Dynamic Height Using Auto Layout
How to Disable Control Center in iOS 7 Programmatically and If Not, What Are Alternatives