考虑具有以下属性的对象Notification
:
id: String
body: String
repeats: Bool
考虑一个Notification
,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
对应的 String 数组?
换句话说,我想编写一个filter()
闭包,并将我的notifications
传递给它,结果输出为:
["1", "2", "3"]
因此,我的过滤器比较运算符应基于属性名称。这可以实现吗?
答案 0 :(得分:4)
filter
在这里不合适。 filter
用于根据某些条件返回通知的子集(例如,仅重复通知)。
您要使用map
来转换数据。
let idList = notifications.map { $0.id }
您可以根据需要组合这些。假设您想要重复通知的ID列表。
let ids = notifications.filter { $0.repeats }.map { $0.id }