首页 > 解决方案 > 如何计算数组中的单个元素?

问题描述

我想计算以下数组中的各个元素:

let b = [
    1, 2, 3,
    [4,5,6],
    [
        [7,8],
        [9,0]
    ]
]

,并且我能够计算以下数组:

let a = [
    [1,2,3],
    [4,5],
    [6,7,8,9]
]

使用以下代码:

protocol DeepCountable {
    var deepCount: Int {get}
}

// conditional conformance
extension Array: DeepCountable where Element: DeepCountable {
    var deepCount: Int {
        return self.reduce(0){$0 + $1.deepCount}
    }
}

extension Int: DeepCountable {
    var deepCount: Int { return 1 }
}

print(a.deepCount)      // 9

我如何对数组 b 做同样的事情?

print( b.deepCount )

标签: swift

解决方案


数组的类型b[Any]Any不是 DeepCountable。现在添加一个deepcount属性Array

extension Array: DeepCountable {
    var deepCount: Int {
        return self.compactMap({ $0 as? DeepCountable }).reduce(0, { $0 + $1.deepCount })
    }
}

let a = [[1,2,3],[4,5],[6,7,8,9]]
print(a.deepCount)//9
let b = [1, 2, 3,[4,5,6],[[7,8],[9,0]]] as [Any]
print(b.deepCount)//10
let c = [1,2,"a","b"] as [Any]
print(c.deepCount)//2

推荐阅读