Count Items in an Array of Arrays?
You can add the nested array counts with
let count = compoundArray.reduce(0) { $0 + $1.count }
Performance comparison for large arrays (compiled and run on a MacBook Pro in Release configuration):
let N = 20_000
let compoundArray = Array(repeating: Array(repeating: "String", count: N), count: N)
do {
let start = Date()
let count = compoundArray.joined().count
let end = Date()
print(end.timeIntervalSince(start))
// 0.729196012020111
}
do {
let start = Date()
let count = compoundArray.flatMap({$0}).count
let end = Date()
print(end.timeIntervalSince(start))
// 29.841913998127
}
do {
let start = Date()
let count = compoundArray.reduce(0) { $0 + $1.count }
let end = Date()
print(end.timeIntervalSince(start))
// 0.000432014465332031
}
You can use joined
or flatMap
for that.
Using joined
let count = compoundArray.joined().count
Using flatMap
let count = compoundArray.flatMap({$0}).count
Since you are asking for a property, I thought I'd point out how to create one (for all collections, while we're at it):
extension Collection where Iterator.Element: Collection {
var flatCount: Int {
return self.reduce(0) { $0 + $1.count } // as per Martin R
}
}
Making this recursive seems to be an interesting exercise.