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