Swift基础12(高级运算符)
2020-01-28 本文已影响0人
SunshineBrother
溢出运算符(Overflow Operator)
swift的算数运算符出现溢出的时会抛出错误
我们可以使用溢出运算符来支持溢出运算。
var a:UInt8 = UInt8.max
a = a + 1
我们使用溢出运算符&=
var a:UInt8 = UInt8.max
a = a &+ 1
print(a) //0
溢出运算符是在达到最大值以后,在重新从最小值开始
当然,你有意在溢出时对有效位进行截断,你可采用溢出运算,而非错误处理。Swfit为整型计算提供了5个&符号开头的溢出运算符。
- 溢出加法 &+
- 溢出减法 &-
- 溢出乘法 &*
- 溢出除法 &/
- 溢出求余 &%
运算符重载
在类、结构体、枚举可以为现有的运算符提供自定义的实现,这个操作叫做:运算法重载
struct Point {
var x:Int, y:Int
static func + (_ p1:Point, _ p2:Point) -> Point{
Point(x: p1.x + p2.x, y: p1.y + p2.y)
}
static func - (_ p1:Point, _ p2:Point) -> Point{
Point(x: p1.x - p2.x, y: p1.y - p2.y)
}
static prefix func - (_ p:Point) -> Point{
Point(x: -p.x, y: -p.y)
}
}
Equatable
想要知道两个实例是否等价,一般走法就是遵守Equatable协议,重载===运算符
struct Person :Equatable{
var age: Int
static func == (_ p1:Person, _ p2:Person) ->Bool{
p1.age == p2.age
}
}
比较运算法Comparable
比较两个实例的大小,一般遵守Comparable协议,重载相应的运算符
struct Student:Comparable {
var age:Int
init(age:Int) {
self.age = age
}
static func < (_ s1:Student, _ s2:Student) -> Bool{
s1.age < s2.age
}
}
自定义运算符
可以自定义新的运算符:在全局作用域使用operator
进行声明
-
prefix operator
前缀运算 -
postfix operator
后缀运算 -
infix operator
中缀运算
struct Point {
var x:Int, y:Int
static prefix func ++ (_ p: inout Point) -> Point{
p = Point(x: p.x + p.x, y: p.y + p.y)
return p
}
}