user2713544 user2713544 - 1 year ago 95
Swift Question

Swift accessing nested array element specified by `NSIndexPath`

If I have nested arrays like this:


How can I access one of the nested elements? I know the
type exists to represent an index path into nested arrays, but how can I access the element specified by a given

Answer Source

I would try a recursive function. However, since you don't know the levels in your tree, you could try something like searching for an specific path.

Let's assume your node class is something like this:

class Node<T> {
    var data: T
    var children: Array<Node<T>>?

    init(data: T, children: Array<Node<T>>?) { = data
        self.children = children

You can make a function like this:

func getNChildren<T>(head: Array<Node<T>>, path: Array<Int>) -> Node<T>? {
    var localPath = path
    // Get the first path and remove it from the array
    let currentPath = localPath.removeFirst()

    if head.indices.contains(currentPath) {
        if localPath.isEmpty {
            // If there's no more in the path, return current element
            return head[currentPath]
        } else {
            if head[currentPath].children != nil {
                // We go looking for children
                return getNChildren(head[currentPath].children!, path: localPath)
            } else {
                // There are no more children, but there are more elements in path, so that level doesn't exist
                return nil

    } else {
        return nil

This function get the element at path if it exists, if not, returns nil (to avoid crashing when looking for non existing indices).

And you can call the function like this:

let elementAt = getNChildren(tree, path: [0, 0, 0, 2])

let elementAt = getNChildren(tree, path: [0, 1, 2, 3, 5, 8, 13, 2, 1, 3, 4, 0, 3])

I know this is not the best approach but maybe it can be useful.


To add data to the Node you have to make this:

let root = Node(data: 0, children: nil)
let child1 = Node(data: 1, children: nil)
let child2 = Node(data: 1, children: nil)
root.children = [child1, child2]
let arr = [root]

Of course you can use any data type as data, that's why the Node class is marked to be generic <T>.

And you can make a function to recursively insert children to the nodes if you feel more comfortable doing that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download