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?
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.
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().
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.
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 .
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]
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With