我想根据机车的parent
数组过滤机车的children
数组;
即:查找所有具有locomotives
的orders
;仅当订单的枚举状态为“ 1”或“ 2”时;并且我正在使用功能代码来尝试过滤数组。
我有各种各样的机车
var locomotives = [Locomotive]
每个机车都有一系列订单
class Locomotive {
var order: [Order] = [Order]()
var state: Int
}
订单是一个结构
enum OrderState: Int {
case initial, existing, sold
}
struct Order {
var state: Int // State can be 0, 1 or 2
var value: OrderState = .initial
}
我希望基于数组locomotives
进行过滤,仅返回order.state
为1或2的订单的机车。
但是我的功能代码返回的是orders
的数组而不是locomotives
的数组
let filter = locos
.filter { (locomotive: Locomotive) -> Bool in
return (locomotive.orders.count > 0)
}
.flatMap { (locomotive: Locomotive) -> [Order] in
locomotive.orders
.filter { (o: Order) -> Bool in
return o.state == .existing || o.state == .sold
}
}
这将返回[Order]
的数组,而不是预期的[Locomotive]
的数组
我想知道如何使以上功能代码为我提供机车列表:
orders
的子数组过滤它>我想根据其子级数组过滤机车的父级数组;即:找到所有有订单的机车;仅当订单的枚举状态为“ 1”或“ 2”时;我正在使用...
您不应该尝试映射到Order,这就是为什么您得到错误类型的结果。相反,您可以直接在机车上进行过滤,例如