eblu
(eblu's full name)
April 19, 2018, 1:48pm
#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)
April 19, 2018, 1:53pm
#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)
April 20, 2018, 7:20am
#4
thanks, I’ll give that a shot.
Tino
(Tino)
April 20, 2018, 10:47am
#5
This pops up from time to time:
To me it would seem more logical as "for x in array? { }" — to parallel
"for case let x? in array { }"
··· On Fri, Feb 10, 2017 at 1:03 PM, Rick Mann via swift-users < <a href="mailto:swift-users@swift.org">swift-users@swift.org</a>> wrote:
I love the idea of for in? (Or even for? In). You should pitch that to
evolution.
Sent from my iPhone
On Feb 10, 2017, at 07:04, Tino Heth <<a href="mailto:2th@gmx.de">2th@gmx.de</a>> wrote:
Is th…
This one started over at swift-users, with a question on how to deal with looping over containers that may be nil.
Imho the beauty of the feature is that it's simple enough to be explained in the subject line, but here is the "long" story:
let test: [Int]? = nil
// this is possible now
if let test = test {
for i in test {
print(i)
}
}
// how it could be written with a modified keyword
for i in? test {
print(i)
}
I've been thinking "in?" had been brought up long ago, but as…
... 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...)