【问题标题】:Filter an array of objects based on field name根据字段名称过滤对象数组
【发布时间】:2019-05-30 20:41:57
【问题描述】:

考虑一个对象Notification,它具有以下属性:

id: String
body: String
repeats: Bool

考虑Notifications、notifications的数组:

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 对应的字符串 数组?

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

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

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

【问题讨论】:

    标签: swift filter higher-order-functions


    【解决方案1】:

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

    你想要map 用于转换数据。

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      相关资源
      最近更新 更多