我正在使用 equatable 协议来比较基于一个名为 的属性的两个自定义对象mediaUID
。
有没有办法在不同属性的比较之间切换?有时我需要按或按likeUID进行
比较。func fetchNotificationsRemoved
mediaUID
var notificationsArray = [NotificationInformation]()
class NotificationInformation {
let type: String
let mediaUID: String?
let commentUID: String?
let likeUID:String?
}
extension NotificationInformation {
func fetchNotificationsRemoved(query: DatabaseQuery) {
NotificationInformation.observeNewNotificationsChildRemoved(query: query) { [weak self] (newNotification: NotificationInformation?) in
guard let strongSelf = self else {return}
guard let notification = newNotification else {return}
if notification.type == "like" {
// How to compare based on likeUID using equatable?
//compare based on likeUID
//get the index of the item of type 'like' in notificationsArray and do something with it
guard let index = strongSelf.notificationsArray.index(of: notification) else {return}
}else if notification.type == "media" {
// How to compare based on mediaUID using equatable?
//compare based on mediaUID
//get the index of the item of type 'media' in notificationsArray
guard let index = strongSelf.notificationsArray.index(of: notification) else {return}
} else if if notification.type == "commentUID" {
....
}
guard let index = strongSelf.notificationsArray.index(of: notification) else {return}
strongSelf.notificationsArray.remove(at: index)
let visibleIndexes = strongSelf.tableView.indexPathsForVisibleRows
let indexPathOfRemovedNotification = IndexPath(row: index, section: 0)
if let indexes = visibleIndexes,
indexes.contains(indexPathOfRemovedNotification) {
strongSelf.tableView.deleteRows(at: [indexPathOfRemovedNotification], with: .fade)
}
}
}
}//end extension
//enables us to compare two objects of type NotificationInformation
extension NotificationInformation: Equatable { }
func ==(lhs: NotificationInformation ,rhs: NotificationInformation) -> Bool {
guard let mediaUIDLeft = lhs.mediaUID else {return false}
guard let mediaUIDRight = rhs.mediaUID else {return false}
return mediaUIDLeft == mediaUIDRight
}