Categories
arrays swift

Adding elements to optional arrays in Swift

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

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.