在Swfit中,Objective-C的运算都是可用的,比如赋值运算符,算术运算符,组合赋值运算符(Compound Assignment Operators),比较运算符,三目运算符(Ternary Conditional Operator),逻辑运算符等,但比Objective-C又多出了两种运算符,下面让我们来看看.
1.空合运算符
var firstName: String = "chen"
var lastName: String?
let name = firstName ?? lastName
print(name)
// name的输出结果为" chen
var firstName: String?
var lastName: String = "xiaoming"
let name = firstName ?? lastName
print(name)
// name的输出结果为: xiaoming
PS: 空合运算符的原理就是先判断左边的变量firstName是否为有值,如果有值就会将firstName的值赋值给name,否则就将lastName赋值给name,但这里的lastName为nil,所以一旦firstName也为空,name也就为nil.
2.区间运算符
所谓的区间运算符其实和我们在Objective-C当中使用for(int i = 0; i <= 10; i++)类似,只是在Swift中,为了更加的简便,所以封装了起来.
for index in 1...5 {
print(index)
}
//index输出结果
//1
//2
//3
//4
//5
3.半区间运算符
除此之外,还有一种叫做半区间运算符,和Objective-C中的for(int i = 0; i < 10; i++)类似.
for index in 1..<5 {
print(index)
}
//index输出结果
//1
//2
//3
//4
好了,这次我们就到这里了,下次继续