3 Comments

  • what about crash?

  • Sadly, I am still using Xcode 6.3.1 for ineffable production reasons, however this more elegant solution worked for me. I’d appreciate your feedback if it could be better (including safer).

    let a = [[1, 2, 3, [4, 5, [6,7,8]]
    let b = [[1, 2, 3, [4, [5,9], [6,7,8]]
    let c = [1, 2, 3, 4, 5]
    import Foundation
    func NSFlatten(inputArray : [NSObject]) -> [NSObject] {
        var result = [NSObject]()
        for item in inputArray {
            if let array = item as? [NSObject] {
                    result += NSFlatten(array)
            } 
            else {
                    result.append(item)
            }
        }
        return result
    }
    NSFlatten(a)  // [1, 2, 3, 4, 5, 6, 7, 8]
    NSFlatten(b)  // [1, 2, 3, 4, 5, 9, 6, 7, 8]
    NSFlatten(c)  // [1, 2, 3, 4, 5]
    • Nice, thanks!