swift - 如何计算数组中的单个元素?
问题描述
我想计算以下数组中的各个元素:
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 )
解决方案
数组的类型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
推荐阅读
- python - 如何使用 Python3 以不隐藏文本的方式缩小 excel 列?
- python - 在 python 中解压 .nii.gz 文件
- postgresql - AWS 和 Datagrip 创建 java.net.unknownhost 异常
- angular - 如何以角度将对象数组从子组件传递到父组件
- haskell - 为什么枚举类型类不是 ord 类型类的子类?
- apache-kafka - 在 Kafka HA 中,为什么需要的最小代理数是 3 而不是 2
- c++ - 一个叫时钟的类
- python - 通过标识而不是相等从 python 列表中删除元素
- reactjs - 如何在 React Router 中使用 Match 对象修复导入错误
- spring-boot - 如何使用 Spring Boot 设置 log4j2 自定义附加程序?