0x7fs
5/28/2015 - 12:41 PM

Swift recursive flatmap

Swift recursive flatmap

func recursiveFlatmap<T, U: AnyObject>(list: [U]) -> [T] {
    var results = [T]()
    results.reserveCapacity(list.count)
    
    for element in list {
        if let subList = element as? [U] {
            results += recursiveFlatmap(subList)
        } else if let element = element as? T {
            results.append(element)
        }
    }
    
    return results
}

let arr: [AnyObject] = [1, [[2]], [3, [4, [5, 6, [7, [8]]]]]]
let flattened: [Int] = recursiveFlatmap(arr) // [1, 2, 3, 4, 5, 6, 7, 8]

// Note that this will throw out any values in the initial multidimensional array that are not of
// what ever type `T` is infered to be. If you want any all elements to be flatmapped regardless of their
// Type, explicitly type `flattened` as `[AnyObject]`, or `[Any]` as best fits your purposes.