antonklimenko
antonklimenko

Reputation: 85

Count elements of nested array swift

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

Upvotes: 2

Views: 1151

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51892

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

Upvotes: 0

gcharita
gcharita

Reputation: 8327

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

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

Upvotes: 5

Related Questions