Daniel Daniel - 6 months ago 8
Swift Question

Array append() to return a new array

I'm working with a struct which has an array. I would like to add a new element to the array, however, the array is immutable so I can't simply append to it. Need to create a new array, append to it and then create a new structure with the extended array. (I know it sounds painful and memory intensive, but it is cleaner and more aligned with the Functional Programming paradigm.)

Is there an append() like function that doesn't mutate the array but instead returns a new one? This would be easier than having to declare a new array and appending to it.

Answer

Try like this:

extension Array {
    func appendToNewArray(newElement: Element) -> Array {
        var result = self
        result.append(newElement)
        return result
    }
}

var ar = [1,2]

let ar2 = ar.appendToNewArray(3)
print(ar2)   // "[1, 2, 3]\n"