Home > Back-end >  Use if-let for more than one condition
Use if-let for more than one condition

Time:06-22

I have a code that looks like so:

   let myItems = presenter?.getShoppingListItems()
    if myFlag.isEnabled() && myItems!.isEmpty {
        //Do something

Now, I want to write this line if myFlag.isEnabled() && shoppingListItems!.isEmpty using if-let.

I tried this:

  let myItems = presenter?.getShoppingListItems()
        if let _ = myFlag.isEnabled(), let myItems = myItems?.isEmpty {
            //Do something 

And this:

    let myItems = presenter?.getShoppingListItems()
        if let myFlag.isEnabled(), let _ = myItems?.isEmpty {
        //Do something

But it's not working. What am I missing here?

CodePudding user response:

Optional binding (if let ...) is supposed to be used when you want to unwrap an optional value and bind it to an identifier. Here, you are not trying to bind anything - you are just trying to check two conditions: myFlag.isEnabled() and myItems?.isEmpty, so a regular if condition will work.

You do need to make sure that the conditions are of type Bool though, not Bool?.

Assuming yo do not want the if statement to run when myItems is nil, you can achieve this by directly comparing the optional myItems?.isEmpty with true.

if myFlag.isEnabled() && myItems?.isEmpty == true {

Alternatively, you can mix optional binding with regular Bool conditions. You can bind myItems, and check isEnabled and isEmpty, all within the same if statement:

if let myItems = presenter?.getShoppingListItems(),
    myFlag.isEnabled(), myItems.isEmpty == true {

}

Or you can bind on myItems?.isEmpty, since that is an optional as well:

if let isEmpty = myItems?.isEmpty,
    myFlag.isEnabled(), isEmpty {

}

If you want the if statement to also be executed when myItems is nil, you can change the condition to != false:

if myFlag.isEnabled() && myItems?.isEmpty != false {

CodePudding user response:

You can try

if let items = presenter?.getShoppingListItems(), items.isEmpty, myFlag.isEnabled() { ... }
  • Related