Ios 安全优雅地删除自定义数组中的元素,Swift
我有一个自定义数组:Ios 安全优雅地删除自定义数组中的元素,Swift,ios,arrays,swift,enums,Ios,Arrays,Swift,Enums,我有一个自定义数组: var customArray = [CustomItem]() 自定义项为: class CustomItem { let firstItem: Enumeration let data: Any // ... } 枚举包含具有不同大小写的枚举。例如案例1、案例2等 我添加了带有append的元素和所有信息,比如firstItem(枚举等) 我需要的是检查我的customArray枚举中是否有给定项。假设我必须在customArray中检查枚举是
var customArray = [CustomItem]()
自定义项为:
class CustomItem {
let firstItem: Enumeration
let data: Any
// ...
}
枚举包含具有不同大小写的枚举。例如案例1、案例2等
我添加了带有append的元素和所有信息,比如firstItem(枚举等)
我需要的是检查我的customArray枚举中是否有给定项。假设我必须在customArray中检查枚举是否存在。example1存在(因为我之前添加了它),以防删除它
最安全、最优雅的方法是什么
额外:如果我想在这个自定义数组的末尾添加一个元素怎么办?如果你想找到一个特定的项目索引,你可以使用firstIndex(of:) 像这样:
let index = customArray.firstIndex(of: CustomItem)
customArray.remove(at: index)
编辑:
您必须使对象与扩展相等:
enter codextension CustomItem: Equatable {
static func ==(lhs: CustomItem, rhs: CustomItem) -> Bool {
return lhs.firstItem == rhs.firstItem
} }
现在,您可以相互比较对象。
这是我在游乐场的代码:
enum Enumeration {
case opt1
case op2
}
struct CustomItem {
var firstItem: Enumeration
let data: Any
}
extension CustomItem: Equatable {
static func ==(lhs: CustomItem, rhs: CustomItem) -> Bool {
return lhs.firstItem == rhs.firstItem
}
}
class ViewController: UIViewController {
var customArray = [CustomItem]()
func searchAndDestory() {
let index = customArray.firstIndex(of: CustomItem.init(firstItem: .op2, data: 0)) ?? 0
customArray.remove(at: index)
}
}
但在我的特定场景中,如何检查customArray中的枚举元素?请参阅我的编辑。我希望我能很好地理解您的问题,这是有帮助的。在我看来,您并没有改进您的解决方案,现在您说如果2个
CustomItem
对象的firstItem
属性相等,即使其他属性不同,它们也是相等的,我认为这是一个错误的假设。例如,如果OP想向集合中添加对象,这可能会产生非常糟糕的后果。在您的例子中:如果让index=customArray.firstIndex(其中:{$0.firstItem=.example1}){customArray.remove(at:index)}