根据字段名称过滤对象数组

时间:2019-05-30 20:41:58

标签: swift filter higher-order-functions

考虑具有以下属性的对象Notification

id: String
body: String
repeats: Bool

考虑一个Notificationnotifications的数组:

let notifications = [Notification(id: "1", body: "body1", repeats: false),
                     Notification(id: "2", body: "body2", repeats: false),
                     Notification(id: "3", body: "body3", repeats: true)]

如何使用高阶filter()函数来检索与每个id对应的 String 数组?

换句话说,我想编写一个filter()闭包,并将我的notifications传递给它,结果输出为:

["1", "2", "3"]

因此,我的过滤器比较运算符应基于属性名称。这可以实现吗?

1 个答案:

答案 0 :(得分:4)

filter在这里不合适。 filter用于根据某些条件返回通知的子集(例如,仅重复通知)。

您要使用map来转换数据。

let idList = notifications.map { $0.id }

您可以根据需要组合这些。假设您想要重复通知的ID列表。

let ids = notifications.filter { $0.repeats }.map { $0.id }