eblu
(eblu's full name)
1
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?
thnx,
-td
mrc
(Marco Capano)
2
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.
-mrc
3 Likes
eblu
(eblu's full name)
4
thanks, I'll give that a shot.
Tino
(Tino)
5
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
(but in most cases, overhead doesn't matter anyways...)