加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

计算数组数组中的项目?

发布时间:2020-12-14 04:52:57 所属栏目:百科 来源:网络整理
导读:如果我有一个声明为的对象 let compoundArray = [ArrayString] 是否有一个属性可以给我在compoundArray中包含的所有数组中的字符串数? 我可以通过在每个数组中添加所有项目来实现: var totalCount = 0for array in compoundArray { totalCount += array.co
如果我有一个声明为的对象

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的属性/方法来做到这一点,不是吗?

谢谢!

解决方法

您可以使用添加嵌套数组计数

let count = compoundArray.reduce(0) { $0 + $1.count }

大型阵列的性能比较(在发布配置中在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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读