If I have an object that is declared as
let compoundArray = [Array<String>]
is there a property that would give me the number of strings in all the arrays contained in compoundArray?
I can do it by adding up all the items in each array within:
var totalCount = 0
for array in compoundArray {
totalCount += array.count }
//totalCount = total items in all arrays within compoundArray
But that seems clunky and it seems that swift would have a property/method of Array to do this, no?
Thanks!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With