代码改变世界

swift自定义运算符

2018-12-13 14:04  法子  阅读(593)  评论(0编辑  收藏  举报

参考:https://www.jianshu.com/p/4f025476701a

//运算符函数要声明在文件的最外层,不能在类里

//声明•的precedencegroup名:PointMultiplicationPrecedence
precedencegroup PointMultiplicationPrecedence {
    associativity: left//左结合
    higherThan: AdditionPrecedence//优先级:比加法高
    lowerThan: MultiplicationPrecedence//优先级:比乘法低
}

infix operator •: PointMultiplicationPrecedence

/// Point的数量积(Option+8)
///
/// - Parameters:
///   - left: One Point
///   - right: Other Point
/// - Returns: (left.x * right.x +  left.y + right.y)
func •(left: CGPoint, right: CGPoint) -> Double {
    return Double(left.x * right.x +  left.y * right.y)
}