自定义操作符中的.
在自定义操作符时,可以以dot(.)开头,这种情况下,操作符后面还可以包含其它的dot(.),如下代码所示:
infix operator .+.
struct Vector2D {
var x: CGFloat
var y: CGFloat
}
extension Vector2D {
static func .+.(left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
}
let vector1 = Vector2D(x: 10, y: 20)
let vector2 = Vector2D(x: 30, y: 10)
let vector = vector1 .+. vector2
vector.x
vector.y
但如果操作符不是以dot
开头,则后面不能再包含dot
,如operator +.+
这个声明会被看成是”+
“操作符后面跟了个”.+
“操作符。编译器会给出如下错误提示:
infix operator +.+ // error: operator with postfix spacing cannot start a subexpression
参考
- [The Swift Programming Language (Swift 4) – Lexical Structure](