user1002909
user1002909

Reputation: 174

How to avoid If let in Swift before doing a for loop

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

Answers (2)

Martin R
Martin R

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

Gustanas
Gustanas

Reputation: 416

You can do something like this:

if let items = doSomethingFuncToGetDataWithOptionalResults() {
    for item in items {
        // so something...
    }
} 

Upvotes: 0

Related Questions