swift中的多个if let和OR条件
我有三个可选值。这些值是从JSON读取的。首先我想用if-let保护这些值,然后我想检查这些值本身 我想检查这些值中是否有一个存在,然后执行一些操作 我知道一条语句中的多个if-let是&&conditions。如何用更少的代码使其成为| |条件 JSON: 以下是一个伪代码:swift中的多个if let和OR条件,swift,Swift,我有三个可选值。这些值是从JSON读取的。首先我想用if-let保护这些值,然后我想检查这些值本身 我想检查这些值中是否有一个存在,然后执行一些操作 我知道一条语句中的多个if-let是&&conditions。如何用更少的代码使其成为| |条件 JSON: 以下是一个伪代码: if let value1 = profile.value1 || let value2 = profile.value2 || let value3 = profile.value3 { // One of t
if let value1 = profile.value1 || let value2 = profile.value2 || let value3 = profile.value3 {
// One of these value is present
if value1 != "null" {
// do something
} else if value2 != "null" {
// do something
} else if value3 != "null" {
// do something
} else {
// No value present
}
} else {
// None of these values is present
}
如果let,请尝试检查变量中的
nil
值,而不是使用
if value1 != nil || value2 != nil || value3 != nil {
// One of these value is present
} else {
// None of these values is present
}
switch (value1, value2, value3) {
case let (.some(value1), _, _):
...
case let (_ , .some(value2), _):
...
case let (_ ,_ , .some(value3)):
...
default:
print("all nil")
}
如果您只想检查至少有一个不是nil
,您可以将其与nil
进行比较
if value1 != nil || value2 != nil || value3 != nil {
// One of these values is present
} else {
// None of these values is present
}
如果要使用的值不是nil
,则它取决于变量的类型。如果它们都是相同的类型,您可以像这样使用nil coalescing
if let value = value1 ?? value2 ?? value3 {
// One of these values is present
} else {
// None of these values is present
}
这将把值
绑定到那些不是nil
的变量中的第一个,但只有当它们是相同类型或符合共享协议时(在这种情况下,您可能必须强制转换它们),它才起作用。现在,您将能够使用value
作为共享类/协议
如果它们是不同的类型,您可以将值强制转换为Any
,但这并不是非常有用,因为您必须检查它的类型并相应地执行操作,相反,我会为每个变量使用If let
。不可能使用If let语句或条件语句。或者,您可以尝试以下选项
首先,
if let _ = value1 {
//One is present
} else if let _ = value2 {
//One is present
} else if let _ = value3 {
//One is present
}
第二,
if let value = value1 ?? value2 ?? value3 {
print(value)
}
一种解决方案是使用带有由变量组成的元组的开关
statmenent
if value1 != nil || value2 != nil || value3 != nil {
// One of these value is present
} else {
// None of these values is present
}
switch (value1, value2, value3) {
case let (.some(value1), _, _):
...
case let (_ , .some(value2), _):
...
case let (_ ,_ , .some(value3)):
...
default:
print("all nil")
}
。一些
用于展开变量
if let value1 = profile.value1, value1 != “” {}
else if value2 = profile.value2, value2 != “” {}
else if value3 = profile.value3, value3 != “” {}
在这里,,
的作用类似于&&
注意:
对于Swift 2,将,
替换为,其中这是否回答了您的问题?不完全是。似乎我最终得到了一个嵌套的多重数和复杂的if-else。我想知道是否有更简单的解决方案。您将如何在outherthen
分支中使用value2
和value3
?你需要它们吗?如果不是,则使用简单的!=nil
对于这两个值就足够了。我将检查并使用任何值(如果存在)。@P2000如果您检查编辑历史记录,问题非常模糊,并且接受的答案不仅没有真正回答问题所问的内容(该答案中没有OR逻辑),而且非常基本,所以我想说OP并没有很好地询问,即使在编辑之后也是如此。如果让value=value1,那就非常好了??值2??value3确实有效:value获得第一个非nil值。但为什么?@P2000这就是所谓的令人兴奋的编码技能。@Raymond祝你好运