1
votes

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

2 Answers

2
votes

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

let attachementsCount = comments.reduce(0) { $0 + $1.attachments.count }
0
votes

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