Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "if let" with logical "or" operator

I'm trying to write the following block of code in a single if let line:

 if let amount = datasource?.incrementForCount?(count) {

        count += amount
    }

    else if let amount = datasource?.fixedIncrement {
        count += amount
    }

when I try something like:

 if let amount = datasource?.incrementForCount?(count) ||  let amount = datasource?.fixedIncrement {

        count += amount
    }

I got a compile time error.

I don't think that where clause is possible for this case.

Is it possible to combine the two if let statements into a single ORed one?

like image 286
JAHelia Avatar asked Dec 13 '15 10:12

JAHelia


2 Answers

Try to use ?? operator:

if let amount = datasource?.incrementForCount?(count) ?? datasource?.fixedIncrement 
{
    count += amount
}

is it possible to combine the 2 if let statements into a single ORed one ?

It is possible to have several let statements like

if let a = optionalA, b = optionalB { ... }

And all of them should return non-nil value to pass.

But if you also want to use a logical condition it:

  1. Could be only the one
  2. Should be placed on the first place, before any let statements
like image 165
Avt Avatar answered Oct 18 '22 23:10

Avt


No, you can't OR two if-let statements, or even an if-let statement with a non if-let condition, because that would completely defeat the purpose of the if-let statement. if-let ensures that you can only enter the body of the statement if the optional could be successfully unwrapped into the variable.

let str:String? = nil
if let s = str || true {
  //s is nil, yet you're still in the if-let body
}

In the above example you would still enter the optional body even if s were nil, in which case you would still have to check whether sis nil or not inside the body, rendering the first if-let check pointless.

like image 33
TheBaj Avatar answered Oct 19 '22 00:10

TheBaj