溢出运算符
- Swift 的算数运算符出现溢出时会抛出运行时错误
- Swift 有溢出运算符(&+、&-、&*),用来支持溢出运算
var min = UInt8.min
print(min &- 1) // 255, Int8.max
var max = UInt8.max
print(max &+ 1) // 0, Int8.min
print(max &* 2) // 254, 等价于 max &+ max
运算符重载
运算符重载:类、结构体、枚举可以为现有的运算符提供自定义的实现
struct Point {
var x: Int
var y: Int
// Point(x: 1, y: 2) + Point(x: 1, y: 2) => Point(x: 2, y: 4)
static func + (p1: Point, p2: Point) -> Point {
return Point(x: p1.x + p2.x, y: p1.y + p2.y)
}
// Point(x: 1, y: 2) - Point(x: 1, y: 2) => Point(x: 0, y: 0)
static func - (p1: Point, p2: Point) -> Point {
return Point(x: p1.x - p2.x, y: p1.y - p2.y)
}
// - Point(x: 1, y: 2) => Point(x: -1, y: -2)
static prefix func - (p: Point) -> Point {
return Point(x: -p.x, y: -p.y)
}
// Point(x: 1, y: 2) += Point(x: 1, y: 2) => Point(x: 2, y: 4)
static func += (p1: inout Point, p2: Point) {
p1 = p1 + p2
}
// ++ Point(x: 1, y: 2) => Point(x: 2, y: 3)
static prefix func ++ (p: inout Point) -> Point {
p += Point(x: 1, y: 1)
return p
}
// Point(x: 1, y: 2) ++ => Point(x: 1, y: 2)
static postfix func ++ (p: inout Point) -> Point {
let tmp = p
p += Point(x: 1, y: 1)
return tmp
}
// Point(x: 1, y: 2) == Point(x: 1, y: 2) => true
static func == (p1: Point, p2: Point) -> Bool {
return (p1.x == p2.x) && (p1.y == p2.y)
}
}
var p1 = Point(x: 10, y: 10)
var p2 = Point(x: 20, y: 20)
var p3 = p1 + p2
print(p3) // Point(x: 30, y: 30)
自定义运算符
不推荐使用自定义运算符,太危险
**
prefix 表示该运算符会位于表达式前面
postfix 表示该运算符会位于表达式后面
infix 表示该操作符会位于两个表达式的中间
prefix operator ~
prefix func ~(v: String?) -> String {
return v == nil ? "" : v!
}
var a: String?
print(~a)
postfix operator ~
postfix func ~(v: String?) -> String {
return v == nil ? "" : v!
}
var a: String?
print(a~)
优先级组
precedencegroup 定义了一个优先级组,表示操作符优先级别
precedencegroup YourPrecedenceGroupName {
/**
较高优先级组的名称,优先级更高的运算符将优先参与运算
eg. MultiplicationPrecedence: *(乘) /(除)
*/
lowerThan: MultiplicationPrecedence
/**
较低优先级组的名称,只可以引用当前模块外的优先级组
eg. AdditionPrecedence: +(加) -(减)
*/
higherThan: AdditionPrecedence
/**
结合性,可选值:left、right、none(默认值)
比如,减法是左边减去右边,而不是右边减去左边
*/
associativity: left
/**
赋值性,可选值:true、false(默认值)
*/
assignment: true
}
举例说明
import Darwin
precedencegroup MyPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator *^ : MyPrecedence
func *^ (lhs: Double, rhs: Double) -> Double {
return pow(lhs, rhs)
}
print(2 *^ 4) // 16.0