Search code examples
arraysswiftmultidimensional-arraysubscript

Swift: simple way to get the first leaf of multidimensional array


Considering a non-empty multidimensional array that has no empty subarrays in it, how can I get the first leaf of it?

Currently, I'm using the following construct:

    let multidimensional = [[[[[[Int]]]]]]()
    let firstLeaf = multidimensional.first?.first?.first?.first?.first?.first
    print(firstLeaf)

Is there any simpler way of achieving the same result, i.e. taking the first leaf out of this array?


Solution

  • I'd create an extension for Array, and use recursion to loop array values until we reach the first element that is not an Array

    extension Array {
        func firstLeaf() -> AnyObject? {
            var res : AnyObject? = self.first as? AnyObject
            if let leaf = res as? Array<Any>
            {
                res = leaf.firstLeaf()
            }
    
            return res
        }
    }
    
    
    print([[[[[[[String]]]]]]]().firstLeaf())       //Optional(<null>)
    print([[[[[[[1,2,3]]]]]]].firstLeaf())          //Optional(1)
    print([[[[[[["B", "A", "R"]]]]]]].firstLeaf())  //Optional("B")