如何计算数组中的各个元素?

时间:2019-04-10 05:59:29

标签: 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 )

4 个答案:

答案 0 :(得分:2)

数组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

答案 1 :(得分:1)

这是可以计算不同类型的通用解决方案

extension Array {
    func countType<T>(_ elemType: T.Type) -> Int {
        var count = 0
        for elem in self {            
            if let _ = elem as? T {
                count += 1
            } else if let arr = elem as? [Any] {
                count += arr.countType(elemType)
            }
        }
        return count
    }
}

用法

let b = [1, 2, 3,[4,5,6],[[7,8],[9,0]]] as [Any]
let c = [1,2,"a","b"] as [Any]

print("Int Count    \(b.countType(Int.self))")
print("Array Count  \(b.countType([Int].self))")
print("Int Count    \(c.countType(Int.self))")
print("String Count \(c.countType(String.self))")
print("Array Count  \(c.countType([Int].self))")

收益

Int Count    10  
Array Count  3  
Int Count    2  
String Count 2  
Array Count  0

答案 2 :(得分:0)

首先,您需要将数组展平为单个数组,然后对该数组进行计数。

let b = [
    1, 2, 3,
    [4,5,6],
    [
        [7,8],
        [9,0]
    ]
]
let flatb = b.flatMap({ $0 })
print(flatb.count)

答案 3 :(得分:0)

以下代码是我根据以上贡献得出的结果:

protocol DeepCountable {
  var deepCount: Int { get }
}

// now any Array is DeepCountable
extension Array: DeepCountable {
  var deepCount: Int {
    return compactMap{ $0 as? DeepCountable }.reduce(0){ $0 + $1.deepCount }
  }
}

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

// test
let a = [[1,2,3],[4,5],[6,7,8,9]]
let b = [1, 2, 3,[4,5,6],[[7,8],[9,0]]] as [Any]
let c = [1,2,"a","b"] as [Any]
let d = [1,2,3,[4,5],[6,7,8,[9, 0]]] as [Any]

print( a.deepCount )  //  9
print( b.deepCount )  // 10
print( c.deepCount )  //  2
print( d.deepCount )  // 10

此代码应与Swift 5配合使用,我已经在Online Swfit Playground上进行过尝试,并且工作正常。