Swift-根据其子顺序数组过滤对象数组?

问题描述 投票:0回答:1

我想根据机车的parent数组过滤机车的children数组;

即:查找所有具有locomotivesorders;仅当订单的枚举状态为“ 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.count> 0)
  • 根据orders的子数组过滤它>

我想根据其子级数组过滤机车的父级数组;即:找到所有有订单的机车;仅当订单的枚举状态为“ 1”或“ 2”时;我正在使用...

arrays swift functional-programming filtering flatmap
1个回答
0
投票

您不应该尝试映射到Order,这就是为什么您得到错误类型的结果。相反,您可以直接在机车上进行过滤,例如

© www.soinside.com 2019 - 2024. All rights reserved.