I wonder why operator overriding is like this.

I wonder how the + function is used directly.

extension CGPoint {
    static func add(lhs: Self, rhs: Self) -> CGPoint {
        CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
    static func +(lhs: Self, rhs: Self) -> CGPoint {
        CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
}
private func testCGPoint() {
    let dummy1 = CGPoint(x: 2, y: 3)
    let dummy2 = CGPoint(x: 4, y: 5)
    let dummy3: CGPoint = .add(lhs: dummy1, rhs: dummy2)
    let dummy4: CGPoint = dummy1 + dummy2
}

in my expectation, I thought that the + function would be used like the add function. i thought this form.

CGPoint.+(lhs: dummy1, rhs: dummy2)

But the + function did not.

How are you doing this?

Answered by mikeyh in 722229022

A Swift expert may provide a better answer.

+ is the builtin standard infix operator equivalent to infix operator +: AdditionPrecedence which you are overriding by extending CGPoint (vs add which is just a plain old static function and cannot be used as an infix operator between two targets).

https://developer.apple.com/documentation/swift/operator-declarations

You can define your own custom infix operator (with naming restricted to specific characters) like this: (although recommend against this)

infix operator : AdditionPrecedence // heavy open centre cross
extension CGPoint {
static func (lhs: Self, rhs: Self) -> CGPoint {
CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
}
private func testCGPoint() {
print(CGPoint(x: 2, y: 3) CGPoint(x: 4, y: 5))
}

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID46 (Custom Operators)

https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID418 (Lexical Structure - Operators)

Accepted Answer

A Swift expert may provide a better answer.

+ is the builtin standard infix operator equivalent to infix operator +: AdditionPrecedence which you are overriding by extending CGPoint (vs add which is just a plain old static function and cannot be used as an infix operator between two targets).

https://developer.apple.com/documentation/swift/operator-declarations

You can define your own custom infix operator (with naming restricted to specific characters) like this: (although recommend against this)

infix operator : AdditionPrecedence // heavy open centre cross
extension CGPoint {
static func (lhs: Self, rhs: Self) -> CGPoint {
CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
}
private func testCGPoint() {
print(CGPoint(x: 2, y: 3) CGPoint(x: 4, y: 5))
}

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID46 (Custom Operators)

https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID418 (Lexical Structure - Operators)

I wonder why operator overriding is like this.
 
 
Q