Daniel Daniel - 7 months ago 13
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.


Try like this:

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

var ar = [1,2]

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