Swift-operator overloading and operator functions

Source: Internet
Author: User

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)varpointer2 = CenterPointer(x:4, y:5)pointer1 += pointer2

Swift-Operator overloading and operator functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.