It is called operator overloading to have an existing operator operate on a custom class and struct or redefine an operation rule for an existing operator.
1, add the custom two coordinate structure body objects by overloading the plus operator:
1234567891011 |
struct CenterPointer
{
var x=0, y=0
}
func + (left:
CenterPointer
, right:
CenterPointer
) ->
CenterPonter
{
return CenterPointer
(x:left.x+right.y, y:left.y+right.y)
}
let pointer1 =
CenterPointer
(x:2, y:3)
let pointer2 =
CenterPointer
(x:4, y:5)
let pointer3 = pointer1 + pointer2
|
2, overload judgment operator for determining whether custom types are equal
1234567 |
func == (left:
CenterPointer
, right:
CenterPointer
) ->
Bool {
return (left.x == right.x) && (left.y == right.y)
}
func != (left:
CenterPointer
, right:
CenterPointer
) ->
Bool {
return !(left == right)
}
|
3, combining operators, combining other operators and assignment operators, note to set the operator left argument to the InOut type
1234567 |
func += ( inout left: CenterPointer , right: CenterPointer ){ left = left + right } var pointer1 = CenterPointer (x:2, y:3) var pointer2 = CenterPointer (x:4, y:5) pointer1 += pointer2 |
Swift-Operator overloading and operator functions