计算数组数组中的项目?

时间:2017-01-13 09:59:52

标签: arrays swift

如果我有一个声明为

的对象
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的属性/方法来执行此操作,不是吗?

谢谢!

3 个答案:

答案 0 :(得分:9)

您可以使用joinedflatMap

使用joined

let count = compoundArray.joined().count

使用flatMap

let count = compoundArray.flatMap({$0}).count

答案 1 :(得分:9)

您可以使用

添加嵌套数组计数
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
}

答案 2 :(得分:1)

由于您要求属性,我想我会指出如何创建一个(对于所有集合,而我们正在处理它):

extension Collection where Iterator.Element: Collection {
    var flatCount: Int {
        return self.reduce(0) { $0 + $1.count } // as per Martin R
    }
}

使这个递归似乎是interesting exercise