Swift operator Operation

Source: Internet
Author: User
Tags comparable



A new feature similar to C + + has been extended in swift, and Swift's operators provide good extensibility, and we can operate on operators, which are actually overrides or overloads of the operator's operations. Note that operator operations are generally manipulated by parameters that are often added to the in-out mode.


+,-(operator overloading)


In our actual development, Swift can customize the operator, not limited to the preset operators, we can overload the + to complete the int with double or flaot Add.
Swift provides the following functions so that int and int can be added:


func + (left:Int,right:Int)->Int{
       return left+right


}
We can reconstruct it completely.


func + (left:Int,right:Double)->Double
{
 return Double(left)+right


}



Implementing the + operator to add elements to an array


func +<T>(var left:[T],right:T)->[T]
  {
       left.append(right)
       return left
  }


After experiments, it seems that Swift does not support the refactoring of =


+ +, – (front and rear operators)


What we said above + and what we didn't say-is the binocular operator, and for the monocular operator, such as ++,–,swift, the operand is placed in front of the monocular operator, which is referred to as the predecessor operator, and the operand is placed after the monocular operator, which is called the post operator.


The reset predecessor operator function must be decorated with the prefix keyword, and the reset post operator must be decorated with the Postfix keyword.
prefix func ++ (operator: Type)-> Type
{

  let result = ++ operator

}

                  `Pre-operator function`

postfix func-(operator: Type)-> Type
{

          let result = operator--
}

                  `Post operator function`


Example:


prefix func ++ <T> (inout array:[T])->[T] {
         array.append(array[array.count-1])
         return array
    }

    var strArr=["iOS","Android","WP"]
    print(++strArr)
+ = (Assignment operator)


The + = assignment operator is provided in the C language, which is actually the addition of the second value to the first value, where the first value requires the use of the in-out pattern.


func += <T>(inout left:[T],right:T)
{
left.append(right)
}

var myList=["iOS","Android"];
myList += "WP"
print(myList)
Comparison operators


The types of int, Double, string, and so on in swift support comparison operators, but if you define a type that requires a comparison size, you need to meet the following two characteristics for a custom type:


    • Comply with equatable, comparable two agreements.
    • Overloads for custom types = = and < two operators.
      Only the = = and < Two operators need to be overloaded with custom types, and Swift can automatically infer the four results of! =, <=, >, >=.

      The format is as follows:

      func  <(las:Type,hrs:Type)->Bool
        {
             let result=lhs<rhs
        }

      Example

      struct WXrect:Equatable,Comparable
       {
           var left:Double
           var top:Double
       var width:Double
           var height:double
          }
      fun ==(las:WXrect,hrs:WXrect)->Bool
      {
       return lhs.width*lhs.height==rhs.width*rhs.height
          }
      fun < (las:WXrect,hrs:WXrect)->Bool
      {
      return ls.width`*`ls.height`<`rhs.width*rhs.height
      }
          let rect1=WXrect(left:2.0,top:3.0,width:5.0,height:4.0)
          let rect2=WXrect(left:8.0,top:23.0,width:2.0,height:8.0)
                            letrect3=WXrect(left:7.0,top:3.0,width:10.0,height:10.0)
      
      print(rect1<rect2)
      print(rect1<=rect2)
      print(rect1!=rect2)
Advanced-Develop your own operators

After accumulating the above, we have mastered the operation of operators, and finally we carry out our own operator development

Two-step fix a custom operator
    1. Declares a new operator.

      The format is as follows:

      prefix | infix | postfix operator operator name {}
      
      prefix: Represents the preceding operator
      infix: stands for binocular operator
      postfix: stands for post operator
      
    2. Provides multiple overloaded operator functions for new operators


If the overloaded operator is a predecessor operator, you will need to add the prefix keyword to the func keyword
If the overloaded operator is a post operator, you will need to add the Postfix keyword to the func keyword

The following is a development of a exponentiation operator: * *



Because multiplication should be a binocular operator, the new operator is declared first: * *


infix operator **{}


Provide overloaded functions for new operators


func ** (base: Int, exponent: Int)-> Int
{
    var result = 1
   for _ in 1 ... exponent
{
  result * = base
}
return result
}

let a = 5
let b = 3
print ("The power of \ (b) of \ (a) is: \ (a ** b)")

How? Swift is strong! Own custom operators


Let's look at a math problem


20+10-5*5*5*2-30


How do you do this problem? I'm a little out of it! O (∩_∩) o haha ~



The side of the math problem is that the operators have sequential execution, so we don't have to have arithmetic rules for our custom operator.



The value of the binding (associativity) has the desirable value of left,right and none. When the left associative operator is written together with the other left-associative operators with the same precedence, it is combined with the left-hand operand. Similarly, the right-associative operator is combined with the right-hand operand. The non-associative operator cannot be written together with other operators of the same precedence. Default priority is 100


infix operator **= { associativity left precedence 140 }
fun ** (base:Int,exponent:Int)
 {

}


Swift operator Operation


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.