Reputation: 174
I have this code on Swift:
let items = doSomethingFuncToGetDataWithOptionalResults()
if let items = items {
for item in items {
// so something...
}
}
Could anyone can help me to avoid if let ...
in this case. It would be better if we could ignore if let
in this case. I feel annoyed when writing this statements every time.
Regards,
Upvotes: 0
Views: 677
Reputation: 539955
Generally, if a function returns an optional then you can use
optional chaining to operate on the result only if it is not nil
.
In your case of an optional array you can use
optional chaining and forEach()
:
doSomethingFuncToGetDataWithOptionalResults()?.forEach { item in
// do something with `item` ...
}
The forEach()
statement will not be executed if the function
returns nil
.
Upvotes: 7
Reputation: 416
You can do something like this:
if let items = doSomethingFuncToGetDataWithOptionalResults() {
for item in items {
// so something...
}
}
Upvotes: 0