user2252374 user2252374 - 7 months ago 29
Swift Question

How to deeply duplicate a multidimensional array in Swift

This question has been asked and answered for a couple other coding languages, but I think I may have a unique problem anyway. So, I want to duplicate a three dimensional array (filled with arbitrary objects). I believe I found that this:

var duplicateArray = originalArray


Does not work, since, for whatever reason, they thought it would a nice safety measure to have this create a duplicate array, but filled with pointers as sub-arrays instead of duplicating the sub-arrays as well. This seems like a strange design choice, since if duplicateArray and originalArray were one-dimensional, this would work as intended. Anyway, so I tried this (where object is some arbitrary object):

var duplicateArray = [[[object]]]()
for x in 0..<originalArray.count {
var tempArrYZ = [[object]]()
for y in 0..<originalArray[x].count {
var tempArrZ = [object]()
for z in 0..<originalArray[x][y].count {
let copiedObj = originalArray[x][y][z]
tempArrZ.append(copiedObj)
}
tempArrYZ.append(tempArrZ)
}
duplicateArray.append(tempArrYZ)
}


This still does not work; all the values in duplicateArray will act like a pointer for their values in originalArray. Perhaps someone has a simple way of deeply duplicating multidimensional arrays, or perhaps someone can find my error?

EDIT: How is this a duplicate of that other question? I'm asking specifically how to "deeply" duplicate. The question that's being referred to nebulously asked about duplicating arrays.

Answer
var duplicateArray = originalArray

Would work if the objects are not of reference type. However, for the reference type you need to actually create the copy of the object with copy. Your original code was pretty close.

var duplicateArray = [[[object]]]()
for x in 0..<originalArray.count {
    var tempArrYZ = [[object]]()
    for y in 0..<originalArray[x].count {
        var tempArrZ = [object]()
        for z in 0..<originalArray[x][y].count {
            let copiedObj = originalArray[x][y][z].copy()
            tempArrZ.append(copiedObj)
        }
        tempArrYZ.append(tempArrZ)
    }
    duplicateArray.append(tempArrYZ)
}