从数组中删除模型对象
Remove the model object from array
在 collectionView 中选择时在数组中添加了模型对象,现在需要从数组中删除取消选择的项目。但是 where 子句不起作用,因为它是在数组中添加的模型,而不是任何普通数据类型。请指导。下面是我的代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if selectedIndex.contains(indexPath.row) {
selectedIndex.removeAll(where: { [=10=] == indexPath.row })
if(userCategories.count > 0){
userCategories.removeAll(where: { [=10=] == 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:
class CategoriesData: Codable {
var id: Int?
var name: String?
var status: String?
}
要比较您需要实现的 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: { [=11=].id == self.categoriesList[indexPath.row].id })
在 collectionView 中选择时在数组中添加了模型对象,现在需要从数组中删除取消选择的项目。但是 where 子句不起作用,因为它是在数组中添加的模型,而不是任何普通数据类型。请指导。下面是我的代码:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if selectedIndex.contains(indexPath.row) {
selectedIndex.removeAll(where: { [=10=] == indexPath.row })
if(userCategories.count > 0){
userCategories.removeAll(where: { [=10=] == 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:
class CategoriesData: Codable {
var id: Int?
var name: String?
var status: String?
}
要比较您需要实现的 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: { [=11=].id == self.categoriesList[indexPath.row].id })