What is the proper way to append an element on the end of an optional array? Let's say I have an optional array, myArray, and I want to append '99' on the end. Append() does not work on a nil array, so the only solution I can find is the following, but it doesn't seem very elegant:
var myArray = [Int]?() if myArray?.count > 0 { myArray?.append(99) } else { myArray = [99] }
Swift Array append() The append() method adds a new element at the end of the array.
Declaring the array as an optional array means that it will not take up any memory at all, whereas an empty array has at least some memory allocated for it, correct? So using the optional array means that there will be at least some memory saving.
You can create an empty array by specifying the Element type of your array in the declaration.
You can use the fact that methods called via optional chaining always return an optional value, which is nil
if it was not possible to call the method:
if (myArray?.append(99)) == nil { myArray = [99] }
If myArray != nil
then myArray?.append(99)
appends the new element and returns Void
, so that the if-block is not executed.
If myArray == nil
then myArray?.append(99)
does nothing and returns nil
, so that the if-block is executed and assigns an array value.
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