简体   繁体   中英

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?

Ie 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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM