swift运算符和c++相同点
swift的位运算符和c的意义一样。
~按位取反
&按位与
|按位或
^按位异或
<<按位左移
>>按位右移
swift的运算符优先级也和c一样。
swift运算符和c++的不同点
swift没有++,--单目运算符,swift增加了c++没有的===、!==等价运算符,区间运算符...,闭合运算符??;此外,swift的算术运算符,默认情况,不会溢出,如果溢出将会在编译阶段报错。
swift算术运算不会溢出,但增加了溢出运算符
&+溢出加法
&-溢出减法
&*溢出乘法
c++运算符重载使用关键子operator来标示,swift没有特别的关键字。
struct Vector2D {
var x = 0.0,y = 0.0
}
extension Vector2D {
static func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
}
let vector = Vector2D(x: 2.0, y: 3.0)
let anotherVector = Vector2D(x: 1.0, y: 0.0)
print(vector + anotherVector)
extension Vector2D {
static prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
}
extension Vector2D {
static func == (left: Vector2D, right: Vector2D) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
static func != (left: Vector2D, right: Vector2D) -> Bool {
return !(left == right)
}
}
extension Vector2D {
static func += (left: inout Vector2D, right: Vector2D) {
left = left + right
}
}
网友评论