Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an element be added to an array conditionally with in-line syntax?

Given an array

let array: [Int]

and a variable

let addElement: Bool

Can an element be added conditionally only if addElement is true using an in-line syntax?

The following works:

let addElement = false
let array = [0, 1, addElement ? 2 : nil] //[0, 1, nil]

But there should be no element at all, not just a nil value. Can that be written in-line like in the example above?

like image 870
Manuel Avatar asked Dec 28 '16 01:12

Manuel


People also ask

How do you conditionally add an object to an array?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

How do you add an element to an array array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

Can you add elements to an array in C++?

Insert Element in Array at a Specific Position To insert an element in an array in C++ programming, you have to ask from user to enter the size and elements for the array.

Can you add values to an array in C?

If you have a code like int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5 .


2 Answers

If you want this inline, you can use compactMap to remove the nil elements:

let addElement = false
let array = [0, 1, addElement ? 2 : nil].compactMap { $0 } //[0, 1]

This has the advantage that you can insert the optional element anywhere within the array:

let addElement = true
let array = [0, addElement ? 2 : nil, 1].compactMap { $0 } //[0, 2, 1]
like image 140
simeon Avatar answered Oct 19 '22 19:10

simeon


While the following method does not define the element within the array's initialization, it does have the advantage of the new index not being pre-defined. I would assume that this is the closest you could get to an in-line solution.

let addElement: Bool = false
var array = [0, 1]
(addElement) ? array.append(2) : Void()
like image 28
Jonathan H. Avatar answered Oct 19 '22 21:10

Jonathan H.