1

Consider an object, Notification, with the following properties:

id: String
body: String
repeats: Bool

and consider an array of 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)]

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?

0

1 Answer 1

4

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.