删除swift对象数组中的重复元素

时间:2018-04-04 21:34:48

标签: ios swift uicollectionview

所以我的应用程序中有一个部分显示了您的关注者将要访问的事件。我成功地拉动了粉丝,并有相应的事件。然后,我将这些事件添加到更大的事件对象数组中。我目前在删除重复项时遇到了问题,我尝试了许多扩展程序,但它似乎并没有起作用。我认为这是因为数组包含具有不同内存地址的不同对象,因此当我比较它们时,无论内容是什么,它们都不相同。我现在已经搞砸了一段时间了,并且无法解决任何问题。如果有人能帮助我,我会很感激。

这是抓取事件并将它们返回到主VC中的数组的方法。

static func showFollowingEvent(for followerKey: String,completion: @escaping (Event) -> Void) {
    //getting firebase root directory
    let ref = Database.database().reference()

    ref.child("users").child(followerKey).child("Attending").observeSingleEvent(of: .value, with: { (attendingSnapshot) in
        print(attendingSnapshot)
        guard var eventKeys = attendingSnapshot.children.allObjects as? [DataSnapshot] else{return}
        for event in eventKeys{
            let dispatchGroup = DispatchGroup()
            dispatchGroup.enter()
            EventService.show(forEventKey: event.key, completion: { (event) in
                dispatchGroup.leave()
                completion(event!)
            })
        }
    }) { (err) in
        print("couldn't grab event info",err)

    }
}  print("couldn't grab event info",err)

    }
}

这是接收事件并在获取事件时重新加载collectionView的函数。

@objc func grabFriendsEvents(){
    print("Attempting to see where your friends are going")
    UserService.following { (user) in
        for following in user {
            print(following.username as Any)
            PostService.showFollowingEvent(for: following.uid, completion: { (event) in
                self.friendsEvents.append(event)
               // self.friendsEvents.append(contentsOf: event)
                // leave here
                self.allEvents2["Friends Events"] = self.friendsEvents.removeDuplicates()
                self.collectionView?.reloadData()
            })

        }  

    }
}

我尝试过这些扩展,这是我在之前的问题中看到的,没有任何效果。

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
    }

    mutating func removeDuplicatesTwo() {
        var result = [Element]()
        for value in self {
            if !result.contains(value) {
                result.append(value)
            }
        }
        self = result
    }
}


import Foundation
import FirebaseDatabase.FIRDataSnapshot

@objc(Event)
class Event:NSObject{
    var key: String?
    let currentEventName: String
    let currentEventImage: String
    let currentEventPromo: String?
    let currentEventDescription: String
    //nested properties
    let currentEventStreetAddress: String
    let currentEventCity: String
    let currentEventState: String
    let currentEventDate: String?
    let currentEventEndDate: String?
    let currentEventTime: String?
    let currentEventEndTime: String?
    let currentEventZip: Int
    var category: String
    //nested properties stop
    var currentAttendCount: Int
    var isAttending = false
    var eventDictionary: [String: Any]{


        let dateDict = ["start:date":currentEventDate, "start:time": currentEventTime,"end:time":currentEventEndTime, "end:date": currentEventEndDate]

        return ["event:name":currentEventName,"event:imageURL" : currentEventImage,
                "event:description": currentEventDescription, "attend:count": currentAttendCount,
                "event:street:address": currentEventStreetAddress,"event:zip": currentEventZip,
                "event:state": currentEventState, "event:city": currentEventCity, "event:promo": currentEventPromo ?? "", "event:date": dateDict, "event:category":category]
    }

    init(currentEventKey: String, dictionary: [String:Any]) {
        self.key = currentEventKey
        self.currentEventName = dictionary["event:name"] as? String ?? ""
        self.currentEventImage = dictionary["event:imageURL"] as? String ?? ""
        self.currentEventDescription = dictionary["event:description"] as? String ?? ""
        self.currentEventPromo = dictionary["event:promo"] as? String ?? ""
        self.currentAttendCount = dictionary["attend:count"] as? Int ?? 0
        self.category = dictionary["event:category"] as? String ?? ""
        //nested properties
        self.currentEventStreetAddress = dictionary["event:street:address"] as? String ?? ""
        self.currentEventCity = dictionary["event:city"] as? String ?? ""
        self.currentEventState = dictionary["event:state"] as? String ?? ""
        self.currentEventZip = dictionary["event:zip"] as? Int ?? 0
        let eventDate = dictionary["event:date"] as? [String: Any]
        self.currentEventDate = eventDate?["start:date"] as? String ?? ""
        self.currentEventTime = eventDate?["start:time"] as? String ?? ""
        self.currentEventEndTime = eventDate?["end:time"] as? String ?? ""
        self.currentEventEndDate = eventDate?["end:date"] as? String ?? ""


    }

    init?(snapshot: DataSnapshot) {
        guard let dict = snapshot.value as? [String : Any],
            let currentEventName = dict["event:name"] as? String,
            let currentEventImage = dict["event:imageURL"] as? String,
            let currentEventDescription = dict["event:description"] as? String,
            let currentEventPromo = dict["event:promo"] as? String,
            let category = dict["event:category"] as? String,
            let currentEventStreetAddress = dict["event:street:address"] as? String,
            let currentEventCity = dict["event:city"] as? String,
            let currentEventState = dict["event:state"] as? String,
            let currentEventZip = dict["event:zip"] as? Int,
            let currentAttendCount = dict["attend:count"] as? Int,
            let eventDate = dict["event:date"] as? [String: Any],
            let currentEventDate = eventDate["start:date"] as? String,
            let currentEventEndDate = eventDate["end:date"] as? String,
            let currentEventTime = eventDate["start:time"] as? String,
            let currentEventEndTime = eventDate["end:time"] as? String
            else { return nil }
        self.key = snapshot.key
        self.currentEventName = currentEventName
        self.currentEventImage = currentEventImage
        self.currentEventDescription = currentEventDescription
        self.currentEventStreetAddress = currentEventStreetAddress
        self.currentEventCity = currentEventCity
        self.currentEventState = currentEventState
        self.currentEventZip = currentEventZip
        self.currentAttendCount = currentAttendCount
        self.currentEventPromo = currentEventPromo
        self.currentEventDate = currentEventDate
        self.currentEventTime = currentEventTime
        self.currentEventEndTime = currentEventEndTime
        self.category = category
        self.currentEventEndDate = currentEventEndDate
    }

    static func ==(lhs: Event, rhs: Event) -> Bool {
        return lhs.key == rhs.key
    }

}

2 个答案:

答案 0 :(得分:1)

您必须使Event类符合Equatable协议

答案 1 :(得分:1)

NSObject类的类将自动为contains()方法调用isEqual()。您可以覆盖超类的实现以适合您的逻辑。

如果你的类要继承NSObject,那么使用:

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)

如果您的类没有继承NSObject,请使其符合Equatable协议。

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)