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) } } // 堆代码 duidaima.com let vector1 = Vector2D(x: 1.0, y: 2.0) let vector2 = Vector2D(x: 3.0, y: 4.0) let vectorSum = vector1 + vector2 print(vectorSum) // 输出结果为Vector2D(x: 4.0, y: 6.0)这个示例中,我们重载了 "+" 运算符,让它可以用于 Vector2D 结构体。现在, "+" 运算符可以接受两个 Vector2D 实例作为参数,并返回一个新的 Vector2D 实例,这个实例的 x 和 y 值是参数的 x 和 y 值的和。
infix operator <- public func <- <T>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.basicType(&left, object: right.value()) case .toJSON: left >>> right default: () } }还有 >>> 运算符:
infix operator >>> public func >>> <T>(left: T, right: Map) { if right.mappingType == .toJSON { ToJSON.basicType(left, map: right) } }
prefix operator √ prefix func √ (number: Double) -> Double { return sqrt(number) } let number = 4.0 print(√number) // 输出结果为2.02. 中缀运算符(Infix Operator)
infix operator **: MultiplicationPrecedence func ** (num: Double, power: Double) -> Double { return pow(num, power) } let result = 2.0 ** 3.0 print(result) // 输出结果为8.03. 后缀运算符(Postfix Operator)
postfix operator -- postfix func -- (num: inout Int) -> Int { num -= 1 return num } var number = 5 print(number--) // 输出结果为4
precedencegroup ExponentiationPrecedence { higherThan: MultiplicationPrecedence associativity: right } infix operator **: ExponentiationPrecedence func ** (num: Double, power: Double) -> Double { return pow(num, power) } let result = 2.0 * 3.0 ** 2.0 print(result) // 输出结果为18.0
这个示例中定义了一个新的优先级组 ExponentiationPrecedence,它的优先级高于乘法运算符的优先级组 MultiplicationPrecedence。然后定义了一个新的中缀运算符 **,并指定它的优先级组为 ExponentiationPrecedence。在计算 2.0 * 3.0 ** 2.0 这个表达式时,由于 ** 运算符的优先级高于 * 运算符,所以先计算 3.0 ** 2.0,得到结果 9.0,然后再与 2.0 相乘,得到结果 18.0。
参考资料
[1]苹果官方网站: https://developer.apple.com/documentation/swift/operator-declarations