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() d
@MartinR's answer is the correct answer, however, just for completeness's sake, if you have an optional and want to do different actions depending on whether it's nor or not you can just check if it's nil (or not nil):
if myArray != nil {
myArray?.append(99)
} else {
myArray = [99]
}
Note that (as you have probably figured out) optional binding doesn't work in your case because the array is a value type: it would create a copy of the array, and append a new element to it, without actually affecting the original array:
// Wrong implementation - the new item is appended to a copy of myArray
if var myArray = myArray {
myArray.append(99)
} else {
myArray = [99]
}