覆盖SPECIFIC数组

时间:2017-04-04 14:57:31

标签: arrays swift enumeration

说你有

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中继承适当的数组概念来覆盖count(或其他)。

但是如何才能覆盖“仅在”数组[Blah]中的数量......这可能吗?

用例 - 也许有更好的方法 - Blah有一些具体的子类型A:Blah,B:Blah .. F:Blah我想过滤[Blah]所以它只返回它们中的某些(比如说“B”当你枚举时,D类型只有“),而计数等只会用于打开的子类型。我很欣赏Swift的切片等等。这里可能很有用。

1 个答案:

答案 0 :(得分:1)

就像人们在评论一样,你真的不想覆盖计数。这里有一些代码说明了为什么它不起作用并提供另一种可能的解决方案。

//: 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