The basic operators and advanced operators to be aware of Swift2.0

Source: Internet
Author: User
Tags bitwise

Previously updated for a period of time on the swift language of the blog, the continuous update of the 6, 7-article appearance. During the period, some of the things in the iOS development of SQLite, Collectionviewcontroller and Reactivecocoa were updated. After two months, it is not a good thing to keep updating the swift language. During the last translation of the book "The Introduction to Swift Programming" (Swift1.0 version, based on Xcode6), the system was engaged in the swift language, and in the following period it intends to keep updating some of the relevant swift languages, But now is the Swift2.0 version, the difference is not small. And now in the work to reconstruct the entire project code, then according to some project examples to update some of the code refactoring blog to communicate with you, and then some of the Android development of some things, of course, analogy with the development of iOS.

Talk less and start the topic of today's blog. Some small partners see today's blog title may Laugh, the basic operators have what to say, as long as the programming, will use the basic operator. This is not false, but today the topic of the blog is not to introduce ++i and i++ difference. Today's blog introduces some of the basic operators that are unique in swift, and these operators give you a light (some of which you crave in OC syntax). Does not accumulate Kuibu not even thousands of miles, does not accumulate the small flow not to become jianghai. Although the need for advanced, but the basis is quite important. The first half of today's blog is the underlying operator that needs attention, with the basic operators of course having advanced operators, followed by some advanced operators. Get a glimpse of Swift2.0 's stuff today (based on Xcode7.1)

I. Basic operators to be aware of

1. Assignment operator (=)

In some languages such as objective-c,c, you are allowed to use the = sign in an expression, as shown below. Testnumber = 20 Returns a value of type bool Yes. Testnumber = 20 is never true in an expression. So the code below prints the contents of the log.

1     Ten ; 2     if  - ) {3         NSLog (@ "testnumber =%ld", testnumber); 4     }

This is not allowed in swift, and the security of swift language can be seen from this point. If you write the above code in swift, you will be quoted the following error. The IDE will prompt you to ask if you should use the = = Budget symbol.

2. Type-safe, implicit type conversions are not allowed

This is also an advantage of the swift language, which is not allowed in the swift language to use implicit type conversions. Implicit type conversions are not allowed even for double types and float types. In objective-c, implicit type conversions are possible. See below for an example:

You can do this in objective-c, and the code below can be compiled. Two types (Float32, Float64) have different data to add, and then implicitly convert the result to another type (Nsinteger).

1     10.0f ; 2     20.0f ; 3     Nsinteger result = FloatNumber1 + floatNumber2;

The above code is shown below in Swift, and the IDE will report an error as follows. The general meaning of the error is that you cannot add data of the Float32 type to the data of the Float64 type. The essential reason is that you are not allowed to implicitly type in the Swift language

In Swift, the above code is given a type-display conversion, and the compilation passes. The corresponding result value is displayed in the playground.

3. The specificity of the modulo operation (%)

Or objective-c do analogy, in the objective-c modulo operation (%) only support integer, if you use a floating-point type in the modulo operation, then the following error is reported. The approximate meaning is that the modulo operation does not support floating-point types, please convert to Nsinteger type.

While the modulo operation in Swift supports floating-point types, the above statement does not error in swift, below is the result value of the above case in playground:

4. Nil aggregation (merge, join) operator (??). )

This operator is a new feature added in Swift. The operator is not in Objective-c. But?? is not the original of Swift, in C # also have?? operator, and usage and swift?? Usage is similar. are used to handle the nil value of the operator, through an instance to introduce, at a glance.

In the example, we first define an optional type of string variable developlanguage to record the development language, and then define a string variable selectlanguage that selects the development language . If the value of Developlanguage is nil, the default language chosen is "Swift". If the value of developlanguage is not nil, force open the value of the optional type and assign the value to the string variable selectlanguage. The specific code looks like this:

Next is the budget symbol?? It's time for the factory, one?? function is the function of if-else in the code above. In other words, the IF-else statement above can be used below?? operator to replace the. The next thing to note is in the?? Operator is not used when using an optional type variable! Forces the value of an optional type to be opened because the?? operator ensures that there is a value in the optional type variable used, and if no value is used, it can be omitted.

5. Comparison operators support strings

In objective-c You can use comparison operators to compare operators, so the compiler won't give an error, but you won't get the results you want. If you use comparison operators directly to compare strings, it is essentially the memory address of the comparison string, see the OBJECTIVE-C code below. It is not difficult to see that the memory address of the string is compared with the output below.

In Swift you can use comparison operators to compare strings, as shown here:

6. Interval operators

The interval operator can represent a range between two values. ... is a closed interval operator, such as A...B, which represents a to B range and includes values of A and B ... < is a semi-open zone, such as a. <b represents the value of the interval A through B, not including B. Its usage is as follows:

The code below uses the closed interval operator 1 ... 10, will cycle 10 times

      

If you change to a half-open interval, it's 9 cycles.

Two. Advanced operators in Swift

Bit arithmetic in 1.Swift

If you have learned the digital circuit course in a college course, you will not be unfamiliar with bit arithmetic. There are also bit operations in many programming languages. The use of bit arithmetic can improve the efficiency of the algorithm, in some efficient algorithms are sometimes used in place operations, and then do not do too much discussion. The next step is to do the bitwise AND, bitwise OR, bitwise XOR, and bitwise inversion of Swift.

(1) Bitwise AND (&)

Each of the binaries is performed and manipulated, so it is called bitwise-with. The arithmetic rules are 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 0. The bitwise and simple usage is to preserve the specified number of bits in the binary, or to clear 0 of the values. Below is a bitwise AND operation of the small instance: 0000_1111 and 1000_1011 bitwise AND operation, is to retain the 1000_1011 four bits. If you want to clear 0 for the specified binary number, you only need to bitwise and operate the value and 0000_0000.

Below is a schematic of the bitwise and in the above code:

(2) bitwise OR (|)

As the name implies, bitwise OR is the binary in which each one is carried out or manipulated, so called bitwise OR. The arithmetic rule is 1 | 1 = 1, 1 | 0 = 1, 0 | 1 = 1, 0 | 0 = 0. bitwise or commonly used to set the value of the specified position to 1. Below is the instance is to put 0000_0011 the first four positions of 1, the last four bits unchanged, so to 1111_0000 with the bitwise OR operation.

The bitwise OR operation schematic diagram is as follows:

(3) Bitwise XOR (^)

An XOR algorithm is also easier to understand, and a simple sentence is the same as 0, with a difference of 1. 1 ^ 1 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1, 0 ^ 0 = 0. It is easy to draw 0 XOR or any number, which is equal to the number itself. 1 XOR or any one number equals this number inversion. Below is an example:

The schematic diagram of the above code is as follows:

The usage of XOR is more, we can use XOR to exchange two number of values when we do not create a temporary variable. Specific as follows:

We can also use the XOR operation to determine whether the two values are equal, and if the two number is different or the value is 0, then two numbers are equal, the exact code is as follows:

1 if 0 {2     print ("swap1 = = swap2")3 }

(4) Bitwise reverse (~)

A value that is different from 1 will be reversed. We can also reverse the value by the bitwise negation operator, the rule of inversion is relatively simple, that is, 0 becomes 1, 1 becomes 0. Below is an example of the inverse operation, which can be seen in the playground value. The instance of the bitwise negation is as follows (the negation of the positive number discussed below, and the negation of negative numbers):

(5) Bitwise left SHIFT (<<) and bitwise Right SHIFT (>>) operation

Positive left and right displacements are filled with diverted, while the negative left is filled by the diverted symbol bit to fill the void. Examples are as follows:

2. Overflow operator

In the swift language, if the value overflows, it will be an error. This can also reflect swift security, and you can use the overflow operator if you want to truncate a valid bit when the value overflows.

The value on overflow operator (&+), about the value overflow operator, does not say much nonsense, directly on the instance. Remove the upper limit of the UInt8 type in the playground and add 1 to it to overflow. If you use the + number directly, you will be given an error. The use of &+ is not the same, the effect is as follows. The use of the underflow operator (&-, &*) of the value is similar to &+, and this is not a repeat. (&/and &%) was not compiled in Xcode7, prompting for this identifier is not found.

3. Operator overloading

Operator overloading is easier to implement in Swift2.0, which is to replace the function name with the operator you want to overload. Below is a small example of operator overloading in Swift. The + operator in Swift does not support the addition of tuples directly, and if you add operations directly to tuples, the following error is reported.

(1) for the infix operator overload, if the + operator is overloaded, then the + operator will support the tuple addition, the specific code and run results are as follows, the + operator original function or unchanged.

(2) to overload the prefix operator, take the-operator as an example. The prefix modifier is prepended to the prefix operator overload before func. If you want to overload the postfix operator, use postfix to decorate, with the prefix operator overload below. The specific code is as follows:

1 //prefix operator overloading2 structPoint {3var x =0.0, y =0.04 }5 6Prefix func-(point:point)Point {7     returnPoint (x:-point.x, y:-point.y)8 }9Let positive = point (x:3.0Y:4.0)TenLet negative =-positive

The resulting output is as follows:

(3) Custom operator: In Swift support to define your own operator, when defining the operator, first use operator to declare the specified identifier, and specify whether the prefix or suffix, and so on, see the following code:

 //    prefix operator  + ++ {}  // 2. Implement  prefix Func + + + + (point:point)-> point{ return  Point (x:point.x + 1 , Y:point.y + 1  );} Let AAA  = Point (x: 1.0 , Y:2.0   = +++aaa;print (add)  //  Point (x:2.0, y:3.0)  

   

The basic operators and advanced operators to be aware of Swift2.0

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.