如何使用可选绑定检查负表达式中的多个值?
How to check multiple values in negative expression with optional binding?
我想检查两个可选变量是否都为空。例如,在 C 中,
int n1 = 1;
int n2 = 2;
if( n1!=0 && n2!=0 ) {
// do something.
}
在 Swift 中有什么方法可以做到这一点吗?
你所谓的可选绑定其实就是if语句多条件。 可选绑定用于当你想从constant/variable定义constant/variable时,可以是nil
。如果不是,则执行 if 语句中的代码。
但是你需要定义两个可选类型的值。你可以用问号 Type?
来做,然后你可以检查两个值是否不是 nil
.
您在 Swift 中的代码:
let n1: Int? = 1
let n2: Int? = 2
if n1 == nil && n2 == nil {
// do something.
}
只需使用 &&
运算符:
// 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
}
您可以通过将它们与 nil
进行比较来检查两个可选值是否 nil
let n1: Int? = nil
let n2: Int? = nil
if n1 == nil, n2 == nil {
print("Nil all the way")
}
用逗号分隔条件等同于使用&&
.
这是使用元组的替代方法:
if (n1, n2) == (nil, nil) {
print("Nil all the way")
}
我想检查两个可选变量是否都为空。例如,在 C 中,
int n1 = 1;
int n2 = 2;
if( n1!=0 && n2!=0 ) {
// do something.
}
在 Swift 中有什么方法可以做到这一点吗?
你所谓的可选绑定其实就是if语句多条件。 可选绑定用于当你想从constant/variable定义constant/variable时,可以是nil
。如果不是,则执行 if 语句中的代码。
但是你需要定义两个可选类型的值。你可以用问号 Type?
来做,然后你可以检查两个值是否不是 nil
.
您在 Swift 中的代码:
let n1: Int? = 1
let n2: Int? = 2
if n1 == nil && n2 == nil {
// do something.
}
只需使用 &&
运算符:
// 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
}
您可以通过将它们与 nil
nil
let n1: Int? = nil
let n2: Int? = nil
if n1 == nil, n2 == nil {
print("Nil all the way")
}
用逗号分隔条件等同于使用&&
.
这是使用元组的替代方法:
if (n1, n2) == (nil, nil) {
print("Nil all the way")
}