[SOLVED] swift: Elegant Way to Map Optional to Array

Issue

I am looking for an elegant way to map an Optional to an Array. What I mean by that is the following:

  • If the Optional is .none, return an empty Array<Wrapped>
  • If the Optional is .some, return a single element Array<Wrapped>

Now this can be done like this

let seq = value.map { [$0] } ?? []

Unfortunately this gets quite ugly and illegible when you want to use it inline.

Is there a better method to accomplish this, without writing a extension?

Solution

How about putting your optional in an array, and compactMap that array with the identity function?

[yourOptional].compactMap { $0 }

As Martin R suggested, you can use CollectionOfOne to save the creation of a throwaway array, at the cost of writing a few more characters:

CollectionOfOne(yourOptional).compactMap { $0 }

Answered By – Sweeper

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *