Adding elements to optional arrays in Swift

swift unwrap optional array
swift declare optional array
swift check if array contains nil
swift optional chaining
swift array with nil values
remove null values from array swift
if let swift
optional binding 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.

Swift Non-Nil Values In An Array Of Optionals, I have an array of String items some of which can be nil . let names = ["Tom", nil, "​Fred"]. The type of names is [String?] - an array of optional  During the registration period, you need to add and remove names as students add and drop the class. var students = ["Ben", "Ivy", "Jordell"] To add single elements to the end of an array, use the append (_:) method.


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

Cannot append element to array of optional - Silver, This pretty simple code, adding an element to an array of optionals, fails to compile in Fire 8.3.2013 with this error: Program.swift(11,14): error  Adding Two Arrays. You can use the addition operator (+) to add two arrays of the same type which will yield a new array with a combination of values from the two arrays as follows −. var intsA = [Int] (count:2, repeatedValue: 2) var intsB = [Int] (count:3, repeatedValue: 1) var intsC = intsA + intsB for item in intsC { print(item) }


My one liner using nil coalescing:

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

Swift - FlatMap unwrapping & flattening optional arrays, Swift - FlatMap unwrapping & flattening optional arrays This can be insanely useful when dealing with arrays with optional elements as you would have to goat.append(player)}print(goat)//["Kobe Bryant", "Michael Jordan",  Add Array: someArray + anotherArray: This returns a new array that contains the elements of someArray first, followed by the elements of anotherArray afterwards. Reverse Array: someArray. reverse This returns an array that has all elements in the reverse order from source array.


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]

How to filter nil values out of the collection types— Swift, Our goal is to filter non-nil elements from optionalElements array and append it to Now we have a dictionary which is contain optional string as a value, A swift Extensions allows you to add functionality to an existing class,  How to modify/add array elements in Swift? You can modify elements of an array by using subscript syntax and assignment operator, i.e. you need to include index of the value you want to update within square brackets after the name of the array followed by the assignment operator and new value . Example 5: Modifying elements of an array


Swift Array Examples, String Arrays, Append to arrays, loop over elements and modify arrays. Swift program that uses first, last optionals let cars: [String] = ["truck", "coupe", "sedan"] // Access first​  array. count contains the number of elements in an array; array.first contains the first item of the array; array.last contains the last item of the array; array.isEmpty is true when the array is empty; You can use array.randomElement() to get a random element from the array (Swift 4.2+).


Array, Swift makes it easy to create arrays in your code using an array literal: simply To add single elements to the end of an array, use the append(_:) method. array, on the other hand, because its Element type is Optional<String> , which does  If you’re looking to append more elements from a different array to your array, you can still use the += operator, or the extend method. anArray += ["Moar", "Strings"] anArray.extend(["Moar", "Strings"]) To insert a single object at the beginning of the array, you can use the insert method. anArray.insert("This String", atIndex: 0)


Collection Types, The type of a Swift array is written in full as Array<Element> , where Element is the type You can create a new array by adding together two existing arrays with This optional value contains the old value for that key if one existed before the  To insert an element to a Set, use insert() method. The syntax is: setName.insert(element). Example Swift programs are provided to explain in detail.