Adding elements to optional arrays in Swift

Instead of using append, try using array merge operator. Because the result is an optional use nil coalescing operator to assign one element array when initial array was nil.

var myArray = [Int]?()

myArray? += [99]
myArray = myArray ?? [99]

I tried to merge it into one line expression but unfortunately Swift doesn't like it

myArray = (myArray? += [99]) ?? [99]

My one liner using nil coalescing:

myArray = (myArray ?? []) + [99]

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.


@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]
}

Tags:

Arrays

Swift