Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to optional arrays in Swift

Tags:

arrays

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] } 
like image 729
Sap Avatar asked Feb 15 '15 21:02

Sap


People also ask

What is append function in Swift?

Swift Array append() The append() method adds a new element at the end of the array.

Is Optional an 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.

How do you create an empty array in Swift?

You can create an empty array by specifying the Element type of your array in the declaration.


1 Answers

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.

like image 61
Martin R Avatar answered Nov 10 '22 15:11

Martin R