使用“如果让"具有逻辑“或"的操作员 [英] Using "if let" with logical "or" operator
本文介绍了使用“如果让"具有逻辑“或"的操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在单个if let
行中编写以下代码块:
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
}
我遇到了编译时错误.
在这种情况下,我认为where
子句是不可能的.
I don't think that where
clause is possible for this case.
是否可以将两个if let
语句合并为一个ORed
语句?
Is it possible to combine the two if let
statements into a single ORed
one?
推荐答案
尝试使用??
运算符:
if let amount = datasource?.incrementForCount?(count) ?? datasource?.fixedIncrement
{
count += amount
}
是否可以将2个if语句组合成一个ORed语句?
is it possible to combine the 2 if let statements into a single ORed one ?
可能有多个let
语句,例如
if let a = optionalA, b = optionalB { ... }
所有这些都应返回非nil值以通过.
And all of them should return non-nil value to pass.
但是,如果您还想使用逻辑条件,则:
But if you also want to use a logical condition it:
- 可能只有一个
- 应该在任何let语句之前放在第一位
这篇关于使用“如果让"具有逻辑“或"的操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文