2

Does anyone know here how to count amount of elements in all nested array of custom objects in Swift?

I.e. I have

[Comments] array which includes [Attachments] array. There may be 100 comments and 5 attachments in each of them. What is the most Swifty way to count all attachments in all comments? I tried few solutions like flatMap, map, compactMap, filter, reduce, but couldn't figure out how to achieve the desire result. The only one that worked for me was typical for in loop.

    for comment in comments {
        attachmentsCount += comment.attachments.count
    }

Is there any better approach to achieve the same? Thanks

2 Answers 2

5

You can use reduce(_:_:) function of the Array to do that:

let attachementsCount = comments.reduce(0) { $0 + $1.attachments.count }
Sign up to request clarification or add additional context in comments.

Comments

0

Here are two ways to do it based on using map

First with reduce

let count = comments.map(\.attachments.count).reduce(0, +)

And one variant using joined

let count = comments.map(\.attachments).joined().count

1 Comment

the interesting part is that he knows that every answer is wrong...

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.