如果我有一个声明为的对象
let compoundArray = [Array<String>]
是否有一个属性可以给我compoundArray 中包含的所有数组中的字符串数量?
我可以通过将每个数组中的所有项目相加来做到这一点:
var totalCount = 0
for array in compoundArray {
totalCount += array.count }
//totalCount = total items in all arrays within compoundArray
但这看起来很笨重,而且 swift 似乎有一个 Array 的属性/方法来做到这一点,不是吗?
Thanks!
您可以添加嵌套数组计数
let count = compoundArray.reduce(0) { $0 + $1.count }
性能比较large数组(在发布配置的 MacBook Pro 上编译并运行):
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)