【问题标题】:Remove the model object from array从数组中删除模型对象
【发布时间】:2021-07-01 06:49:33
【问题描述】:

在 collectionView 中选择时在数组中添加模型对象,现在需要从数组中删除取消选择的项目。但是 where 子句不起作用,因为它是在数组中添加的模型,而不是任何正常的数据类型。请指导。以下是我的代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if selectedIndex.contains(indexPath.row) {
        selectedIndex.removeAll(where: { $0 == indexPath.row })
      
        if(userCategories.count > 0){
           
            userCategories.removeAll(where: { $0 == self.categoriesList[indexPath.row] }) // Error in this line
            print(userCategories)
        }
    }else {
        selectedIndex.append(indexPath.row)

        userCategories.append(self.categoriesList[indexPath.row])
        print(userCategories)
    }
}

错误是:

Binary operator '==' cannot be applied to two 'CategoriesData' operands

模型类:

class CategoriesData: Codable {
var id: Int?
var name: String?
var status: String?
}

【问题讨论】:

  • 显示存储在 userCategories 数组中的模型
  • 类 CategoriesData: Codable { var id: Int?变量名称:字符串?变量状态:字符串?

标签: ios arrays swift xcode uicollectionview


【解决方案1】:

要比较 2 个自定义对象,您需要实现 Equatable

class CategoriesData: Codable , Equatable {
    var id: Int?
    var name: String?
    var status: String?
    static func == (lhs: CategoriesData, rhs: CategoriesData) -> Bool {
        lhs.id == rhs.id
    }
}

userCategories.removeAll(where: { $0.id == self.categoriesList[indexPath.row].id })  

【讨论】:

  • 请详细说明,没看懂
  • 编译器应该根据什么来决定对象是否相等???这是错误消息实现 Equatable 的原因
  • 明白你的意思,但是,该类已经在使用 Codable,如何实现 Equitable 以及
  • 同时更新我的​​问题
  • 没想到它像一个魅力,我浪费了一个多小时,不敢相信
猜你喜欢
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 2016-11-26
  • 2016-05-19
  • 2011-04-04
  • 2013-03-16
相关资源
最近更新 更多