Swift 比较运算符
Swift 4支持C语言的所有标准比较运算符。
- 等于(
a == b
) - 不等于(
a != b
) - 大于(
a > b
) - 小于(
a < b
) - 大于或等于(
a >= b
) - 小于或等于(
a <= b
)
注意:Swift 4还提供了两个标识符(===
和!==
),用于测试两个对象引用是否指向同一个对象实例。
每个比较运算符都返回一个Bool值,用于指定语句是否为真。
1 == 1 // true because 1 is equal to 1
2 != 1 // true because 2 is not equal to 1
2 > 1 // true because 2 is greater than 1
1 < 2 // true because 1 is less than 2
1 >= 1 // true because 1 is greater than or equal to 1
2 <= 1 // false because 2 is not less than or equal to 1
比较运算符在条件语句中使用,就像if语句一样。
示例1
let name = "world"
if name == "world" {
print("hello, world")
} else {
print("I am sorry. I don't recognize you")
}
// Prints "hello, world", because name is indeed equal to "world".
输出:
hello, world
示例2
let name = "world"
if name == "JavaTpoint" {
print("hello, world")
} else {
print("I am sorry. I don't recognize you")
}
// Prints "I am sorry. I don't recognize you", because name is not equal to "world".
输出:
I am sorry. I don't recognize you