swfit:运算符重载 Operator Methods

Operator Methods

Classes and structures can provide their own implementations of existing operators. This is known as overloading the existing operators.

 

  1. struct Vector2D {
  2. var x = 0.0, y = 0.0
  3. }
  4. extension Vector2D {
  5. static func + (left: Vector2D, right: Vector2D) -> Vector2D {
  6. return Vector2D(x: left.x + right.x, y: left.y + right.y)
  7. }
  8. }

The type method can be used as an infix operator between existing Vector2D instances:

  1. let vector = Vector2D(x: 3.0, y: 1.0)
  2. let anotherVector = Vector2D(x: 2.0, y: 4.0)
  3. let combinedVector = vector + anotherVector

 

Prefix and Postfix Operators

The example shown above demonstrates a custom implementation of a binary infix operator. Classes and structures can also provide implementations of the standard unary operators. Unary operators operate on a single target. They are prefix if they precede their target (such as -a) and postfix operators if they follow their target (such as b!).

 

Custom Operators

You can declare and implement your own custom operators in addition to the standard operators provided by Swift. For a list of characters that can be used to define custom operators, see Operators.

New operators are declared at a global level using the operator keyword, and are marked with the prefixinfix or postfix modifiers:

  1. prefix operator +++

The example above defines a new prefix operator called +++. This operator does not have an existing meaning in Swift, and so it is given its own custom meaning below in the specific context of working with Vector2D instances. For the purposes of this example, +++ is treated as a new “prefix doubling” operator. It doubles the x and y values of a Vector2D instance, by adding the vector to itself with the addition assignment operator defined earlier. To implement the +++ operator, you add a type method called +++ to Vector2D as follows:

  1. extension Vector2D {
  2. static prefix func +++ (vector: inout Vector2D) -> Vector2D {
  3. vector += vector
  4. return vector
  5. }
  6. }
  7. var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
  8. let afterDoubling = +++toBeDoubled
  9. // toBeDoubled now has values of (2.0, 8.0)
  10. // afterDoubling also has values of (2.0, 8.0)

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值