我正在使用一个充满结构的数组:
struct CartModel: Codable {
var product_id: Int
var line_subtotal: Float
var line_total: Float
var line_tax: Float
var line_subtotal_tax: Float
var key: String
var quantity: Int
}
static var fullCart = [CartModel]()
现在我试图从数组中删除其中一个。
我尝试使用 fullCart.index(of:)
,但出现以下错误:
Argument labels '(of:, _:)' do not match any available overloads
我希望使用 fullCart.remove(at:)
,但由于无法找到正确的索引,我不确定如何删除正确的项目。
最佳答案
您还可以通过 index(where:)
查找索引然后从数组中删除项目:
if let index = fullCart.index(where: { $0.product_id == otherCartModel.product_id }) {
fullCart.remove(at: index)
}
或符合Equatable
协议(protocol)和使用 index(of:)
:
struct CartModel: Codable, Equatable {
...
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.product_id == rhs.product_id
}
}
if let index = fullCart.index(of: otherCartModel) {
fullCart.remove(at: index)
}
关于arrays - 如何快速从数组中删除特定项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49538541/