Reputation: 905
Consider an object, Notification
, with the following properties:
id: String
body: String
repeats: Bool
and consider an array of Notification
s, notifications
:
let notifications = [Notification(id: "1", body: "body1", repeats: false),
Notification(id: "2", body: "body2", repeats: false),
Notification(id: "3", body: "body3", repeats: true)]
How can I use the higher-order filter()
function to retrieve an array of Strings corresponding to each id
?
In other words, I would like to write a filter()
closure to which I pass my notifications
and the resulting output is:
["1", "2", "3"]
Therefore, my filter comparison operator should be based on the property name. Is this achievable?
Upvotes: 1
Views: 154
Reputation: 318774
filter
is not the appropriate tool here. filter
would be for returning a subset of the notifications based on some criteria (such as only repeating notifications, for example).
You want map
which is used to transform data.
let idList = notifications.map { $0.id }
You can combine these as needed. Let's say you wanted the list of ids for the repeating notifications.
let ids = notifications.filter { $0.repeats }.map { $0.id }
Upvotes: 4