[英]How to check multiple values in negative expression with optional binding?
I want to check if two optional variables are all null.我想检查两个可选变量是否都为空。 For example, in C,例如,在 C 中,
int n1 = 1;
int n2 = 2;
if( n1!=0 && n2!=0 ) {
// do something.
}
Is there any way to do this in Swift?有什么办法可以在 Swift 中做到这一点吗?
What you call optional binding is actually just if statement with multiple conditions.您所说的可选绑定实际上只是具有多个条件的if 语句。 Optional binding is used when you want to define constant/variable from constant/variable which can be nil
.当您想从可以是nil
常量/变量定义常量/变量时,使用可选绑定。 When isn't, code inside if statement gets executed.如果不是,则执行 if 语句中的代码。
But you need to define two values with optional type.但是您需要使用可选类型定义两个值。 This you can do with question mark Type?
这你可以用问号Type?
做Type?
and then you can check if both values aren't nil
.然后你可以检查两个值是否都不是nil
。
Your code in Swift:您在 Swift 中的代码:
let n1: Int? = 1
let n2: Int? = 2
if n1 == nil && n2 == nil {
// do something.
}
Just use the &&
operator:只需使用&&
运算符:
// here are the optional variables:
var a: Int? = nil
var b: Int? = nil
if a == nil && b == nil {
// this will only run if both a and b are nil
}
You can check if two optionals are nil
by comparaing them to nil
您可以通过将两个选项与nil
进行比较来检查它们是否为nil
let n1: Int? = nil
let n2: Int? = nil
if n1 == nil, n2 == nil {
print("Nil all the way")
}
Separating conditions with a comma is equivalent to using &&
.用逗号分隔条件等价于使用&&
。
Here is an alternative using tuples:这是使用元组的替代方法:
if (n1, n2) == (nil, nil) {
print("Nil all the way")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.