0

I have a following code, which copies an array of Rider objects, and appends a new Rider object if it exists.

let riders:[Rider] = getRiders()
let newRider:Rider? = mayGetNewRider()
var ridersPlus = riders
if let rider = newRider {
   ridersPlus.append(rider)
}

I am looking for a better (simpler and easier to read) way to write this logic, which also allows me to define ridersPlus as "let" variable.

I am looking for something like below (which is invalid, because I made up the ??? syntax, which produces an empty array of newRider is nil).

let riders:[Rider] = getRiders()
let newRider:Rider? = mayGetNewRider()
let ridersPlus = riders + [newRider???]

2 Answers 2

1

How about

let ridersPlus = riders + [newRider].compactMap {$0}

(Note that before Swift 4, compactMap would be called flatMap. You didn't say what Swift version you are using.)

Sign up to request clarification or add additional context in comments.

Comments

1

You do it with map and the nil coalescing operator ??:

let ridersPlus = riders + (newRider.map {[$0]} ?? [])

map when called on an Optional value evaluates the given closure when the Optional instance is not nil, passing the unwrapped value as a parameter. If the Optional is nil, the result of the map is nil. Combining that with the nil coalescing operator, the resulting Optional array can be unwrapped or replaced with [] and then added to the riders array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.