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.
To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array.
If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.
Sometimes you need to append one or more new values at the end of an array. In this situation the push() method is what you need. This method accepts an unlimited number of arguments, and you can add as many elements as you want at the end of the array. The push() method also returns the new length of the array.
Would you not just add two arrays together?
let originalArray: [Type] = ...
let objectToAppend: Type = ...
let newArray = originalArray + [objectToAppend]
Or, in an extension, if you prefer:
extension Array {
func arrayByAppending(o: Element) -> [Element] {
return self + [o]
}
}
Try this:
extension NSArray {
func myAppend(arrToAppend: NSArray) -> NSArray {
let r : NSMutableArray = NSMutableArray(array: self)
r.addObjectsFromArray(arrToAppend as [AnyObject])
return r.copy() as! NSArray
}
}
for a single object
extension NSArray {
func myAppend2(objToAppend: AnyObject) -> NSArray {
let r : NSMutableArray = NSMutableArray(array: self)
r.addObject(objToAppend)
return r.copy() as! NSArray
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With