For loops with optional arrays, is there a better, less wordy way?

I have a bunch of optional arrays in my current project and to traverse the array it’s become very wordy:

if let a = optionalArray{
for anItem in a{
// doo stuff here.

because :

for anItem in optionalArray?{
// stuff

causes an error.
am I missing something? is this intended behavior? who can I make suggestions to in that case?


I think this is intended. You could use forEach instead, with optional chaining like this:

optionalArray?.forEach { /*do stuff here*/}

Or, if you want to use the classic for -> in approach you could do like this:

for element in optionalArray ?? [] {
      /* do stuff here */

Both solutions do nothing if the array is nil, which I think is the behavior you’re looking for.



thanks, I’ll give that a shot.

This pops up from time to time:

... and there are more threads with possible "workarounds".

Is what I do most of the time as well -- although I alway feel bad because I never checked if this actually creates an empty array with the associated overhead compared to if let :slight_smile: (but in most cases, overhead doesn't matter anyways...)