Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eonist/a21a491496409ed3e203d3f47fdbe35c to your computer and use it in GitHub Desktop.
Save eonist/a21a491496409ed3e203d3f47fdbe35c to your computer and use it in GitHub Desktop.
Swift recursive flatmap (Alternative version)
protocol AnyArray{}/*<--Neat trick to assert if a value is an Array, use-full in reflection and when the value is Any but really an array*/
extension Array:AnyArray{}//Maybe rename to ArrayType
func recFlatMap<T>(_ arr:[AnyObject]) -> [T]{
var result:[T] = []
Swift.print("arr.count: " + "\(arr.count)")
arr.forEach{
if($0 is AnyArray){
let a:[AnyObject] = $0 as! [AnyObject]
result += recFlatMap(a)
}else{
result.append($0 as! T)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment