Extending Collection with a recursive property/method that depends on the element type
In the context of this question , I though about how one could implement a property or method that counts across all nesting levels in collections. Intuitively, something this should work: extension Collection { var flatCount: Int { if self.count == 0 { return 0 } else if self.first is Collection { // .Iterator.Element: Collection return self.reduce(0) { (res, elem) -> Int in res + (elem as! Collection).flatCount // ERROR } } else { return self.reduce(0) { (res,_) in res + 1 } } } } However, we are not allowed to cast values to protocol types that have associated types. So I thought to make