我在以下结构中有3个模型
class Option {
var id : String = ""
var quantity : Int = 0
init(_id: String, _quantity: Int) {
id = _id
quantity = _quantity
}
}
class RemovedItems {
var id : String = ""
var quantity : Int = 0
init(_id: String, _quantity: Int) {
id = _id
quantity = _quantity
}
}
class ProductOrder {
var guid : String = ""
var sizeHid : String = ""
var options : [Option] = []
var removed : [RemovedItems] = []
init(id: String, sizeId: String, _options: [Option], removedItems: [RemovedItems]) {
guid = id
sizeHid = sizeId
options = _options
removed = removedItems
}
}
现在我有一个ProductOrder列表
[ProductOrder]
我想通过选项和删除列表来过滤此列表。
productOrder1具有[A1,A2]的选项列表,并使用[C1]
删除productOrder2具有[A1,A2]的选项列表,并使用[]
删除productOrder3具有[A1]的选项列表,并使用[C1]
删除productOrder4具有[A1,A2]的选项列表,并使用[C1]
删除
因此结果将显示productOrder1,productOrder4是相同的,因为它们具有相同的选项和删除的列表。
我可以通过循环遍历数组并使用一些逻辑来实现这一点,但我希望能够通过更高阶函数和序列来实现这一点。总之,我想清理一下我的代码。那么,怎么做呢?
答案 0 :(得分:1)
以下是基于Equatable
和forEach
的解决方案,一次性过滤:
<强>模型强>
class Option: Equatable {
var id : String = ""
var quantity : Int = 0
static func == (lhs: Option, rhs: Option) -> Bool {
return lhs.id == rhs.id
}
init(_id: String, _quantity: Int) {
id = _id
quantity = _quantity
}
}
class RemovedItems: Equatable {
var id : String = ""
var quantity : Int = 0
static func == (lhs: RemovedItems, rhs: RemovedItems) -> Bool {
return lhs.id == rhs.id
}
init(_id: String, _quantity: Int) {
id = _id
quantity = _quantity
}
}
class ProductOrder: Equatable {
var guid : String = ""
var sizeHid : String = ""
var options : [Option] = []
var removed : [RemovedItems] = []
static func == (lhs: ProductOrder, rhs: ProductOrder) -> Bool {
return lhs.options == rhs.options && lhs.removed == rhs.removed && lhs.guid != rhs.guid
}
init(id: String, sizeId: String, _options: [Option], removedItems: [RemovedItems]) {
guid = id
sizeHid = sizeId
options = _options
removed = removedItems
}
}
<强>测试强>
var orderProducts = [ProductOrder]()
let o1 = Option(_id: "o1", _quantity: 1)
let o2 = Option(_id: "02", _quantity: 1)
let r1 = RemovedItems(_id: "r1", _quantity: 1)
orderProducts.append(ProductOrder(id: "if3gpfubicurnwbviprgrv", sizeId: "_1234", _options: [o1, o2], removedItems: [r1]))
orderProducts.append(ProductOrder(id: "if3gpfubicurnwbviprgrb", sizeId: "_1234", _options: [o1, o2], removedItems: [r1]))
orderProducts.append(ProductOrder(id: "if3gpfubicurnwbviprgrc", sizeId: "_1234", _options: [o2], removedItems: []))
orderProducts.append(ProductOrder(id: "if3gpfubicurnwbviprgrd", sizeId: "_1234", _options: [o2], removedItems: []))
orderProducts.append(ProductOrder(id: "if3gpfubicurnwbviprgrj", sizeId: "_1235", _options: [o2], removedItems: [r1]))
var results = [[ProductOrder]]()
orderProducts.forEach {
if let lastValue = results.last?.last, lastValue == $0 {
results[results.count - 1].append($0)
} else {
results.append([$0])
}
}
print(results) //[[1,2], [3,4], [5]]