Reputation: 2817
I am using the below code to update my array. My requirement is that the new data does not exist, for that I am using the .contains method.
This method is not working properly when I change the viewcontroller and come again on same page. It returns false
and I keep getting duplicate results due to that.
Is this an issue related to the custom object?
if let list = rooms as? [[String : AnyObject]]
{
// self.roomList = [Room]()
for item in list
{
let roomStr = json(from: item)
let roomObj : Room = Room(JSONString: roomStr!)!
if !self.roomList.contains(roomObj)
{
self.roomList.append(roomObj)
}
}
DispatchQueue.main.async {
//First sort by name and then sort by default room..
self.roomList.sort { $0.getRoomName()! < $1.getRoomName()! }
self.roomList.sort { $0.getDefaultRoom()! && !$1.getDefaultRoom()! }
self.LoadRoomsTableView.reloadData()
self.hideActivity()
}
}
Any idea how to solve it or any suggest on the effiecient way for add/update the data in array with swift.
Upvotes: 0
Views: 658
Reputation: 2198
You have to make sure your Room
class/struct implements the protocol Equatable
.
Example:
class Room {
let rooms: Int
let color: String
init(rooms: Int, color: String) {
self.rooms = rooms
self.color = color
}
}
extension Room: Equatable {
func ==(lhs: Room, rhs: Room) -> Bool {
return lhs.rooms == rhs.rooms && lhs.color == rhs.color
}
}
If you had a struct
and Swift > 4.1+ you would not have this problem, as the ==
is kindly provided by Swift. Thanks Vadian for the reminder.
Upvotes: 2