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?
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:
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 s
is nil or not inside the body, rendering the first if-let
check pointless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With