运算符基本概念
1、一元运算符对一个目标进行操作,一元前缀运算符,如:!b,一元后缀运算符,如:b!
2、二元运算符对两个目标进行操作,如a+b,因为它出现在两个目标之间,所以是中缀
3、三元运算符操作三个目标,Swift语言中,只有一个三元运算符,三元条件运算符(a ? b : c)
Swift中对运算符的改进:
1、支持C语言中大多数标准运算符,同时也增加了一些排除常见代码错误的能力
2、赋值符号(=)不会返回值,防止它被用于(==)的意图上面
3、算数符号(+、-、*、/、%以及其他)可以检测并阻止值溢出,以避免你在操作比储存类型允许的范围更大或更小的数字时得到的各种奇怪的结果
赋值运算符
1、赋值运算符将一个值赋给另一个
2、如果赋值符号右侧是拥有多个值的元组,它的元素将会一次性地拆分成常量或者变量
3、Swift的赋值符号自身不会返回值
let a = 1
let b = 1
//赋值运算符不会返回值 if b = a 这样写就报错了
if b == a {
print("do something")
}
算术运算符
标准运算符
1、+ - * /
2、加法运算符同时支持String的拼接
3、Swift的算术运算符默认不允许值溢出
余数运算符
1、a % b 表示a除以b的余数
2、a是负数时也可以用相同的方法来计算
3、当b小于0时,它的正负号就会被忽略,也就是说 a % b 和 a % -b得到的余数是相同的
let c = 9 + 4
print(c)
let d = 9 % -4
print(d)
let e = -9 % 4
print(e)
let f = 9 * 4
print(f)
let g = 8 / 4
print(g)
打印结果:
13
1
-1
36
2
溢出运算符
在默认情况下,当向一个整数赋超过它容量的值时,Swift会报错而不是生成一个无效的数,给我们操作过大或者过小的数的时候提供了额外的安全性。
溢出加减乘:&+ &- &*
//UInt8范围:0-255
let num1:UInt8 = 250
let num2 = num1 &+ 10 //250+10超过了UInt8的范围,上溢出了,&+
print(num2) //4
let num3:UInt8 = 0
let num4 = num3 &- 1 //下溢出了,&-
print(num4) //255
let num5:Int8 = -128
let num6 = num5 &- 1
print(num6) //127
打印结果:
4
255
127
合并运算符
1、合并空值运算符(a ?? b),如果可选项a有值则展开,如果没有值,是nil,则返回默认值b
2、表达式a必须是一个可选类型,表达式b必须与a的储存类型相同
let a:Int? = nil
let b = 2
print(a ?? b)
print(addTwoNum(num1: a, num2: b))
func addTwoNum(num1:Int?,num2:Int?) -> Int {
return (num1 ?? 0) + (num2 ?? 0) //合并空值运算符
}
打印结果:
2
2
区间运算符
闭区间运算符:1…5
半开区间运算符:a…<b
单侧区间:[2…] […<2]
倒序索引:reversed()
let range = 0..<4
for i in range {
print(i)
}
let names = ["zs","ls","ww","zl"]
for name in names[..<2]
{
print(name)
}
var welcome = "hello,world"
let range2 = welcome.startIndex...welcome.index(welcome.endIndex, offsetBy: -6)
welcome.removeSubrange(range2)
print(welcome)
welcome = "hello,world"
let range3 = "a"..."z"
for c in welcome
{
if !range3.contains(String(c))
{
print("\(c) 不是小写字母")
}
}
for i in (0...3).reversed()
{
print(i)
}
打印结果:
0
1
2
3
zs
ls
world
, 不是小写字母
3
2
1
0