覆盖特定数组中的计数(或其他)

Override count (or whatever) in a SPECIFIC array

假设你有

class Blah {
}

然后我要 [Blah]

但是,Blah 数组的工作方式与普通数组略有不同。

比如我想让count这样工作,比如说

override count {
  c = super.count // an ordinary count of the array
  y = count of items where blah.color = yellow
  return y
}

当然,我知道如何通过子类化 Swift 中适当的数组概念来覆盖计数(或其他)。

但是我如何覆盖计数 "only in" 数组 [Blah] ...这可能吗?

用例 - 也许有更好的方法 - Blah 有许多具体的子类型 A:Blah、B:Blah .. F:Blah 我想过滤 [Blah] 所以它只 returns 其中某些(例如,"B and D types only"),当您枚举时,计数等将仅针对打开的子类型。我很欣赏 Swift 的切片等可能与这里相关。

就像人们在评论一样,您真的不想覆盖计数。下面是一些代码,说明了为什么这行不通,并提供了另一种可能的解决方案。

//: Playground - noun: a place where people can play

class Blah {

    let include: Bool

    init(include: Bool) {
        self.include = include
    }

}

// This code "works", but you'll get an error that "count" is ambiguous because
// it's defined in two places, and there's no way to specify which one you want
//extension Array where Element: Blah {
//
//    var count: Int {
//        return reduce(0) { result, element in
//            guard element.include else {
//                return result
//            }
//
//            return result + 1
//        }
//    }
//
//}

// But you could add a helper to any blah sequence that will filter the count for you
extension Sequence where Iterator.Element: Blah {

    var includedBlahCount: Int {
        return reduce(0) { result, blah in
            guard blah.include else {
                return result
            }

            return result + 1
        }
    }

}

let blahs = [Blah(include: false), Blah(include: true)]
print(blahs.count) // 2
print(blahs.includedBlahCount) // 1