Swift basic Operators

Source: Internet
Author: User

Operators are special symbols or phrases for checking, changing, and merging values. For example, the plus sign + adds two numbers (for example, let I = 1 + 2 ). Complex operations such as logic and operators & (for example, if entereddoorcode & passedretinascan), or convenient operator auto-incrementing operator ++ I that adds I value to 1.

Swift supports most operators in the Standard C language and improves many features to reduce regular encoding errors. For example, the value assignment operator (=) does not return values, so as to prevent errors caused by writing the place where the equal operator (=) is to be judged as a value assignment. Numeric operators (+,-, *,/, %, and so on) detect non-allowed value overflow, to avoid the exception caused by the variable being greater than or less than the range that its type can carry. Of course, you can use the swift overflow operator to implement overflow. For more information, see overflow operators.

Unlike the C language, in swift, you can perform the remainder operation (%) on floating point numbers. Swift also provides the interval operators that do not exist in the C language to express the values between two numbers, (.. B and... b). This facilitates us to express the values in a range.

This section only describes basic operators in swift. Advanced operators include advanced operators, how to customize operators, and how to overload operators of custom types.

Terms

An operator has one, two, and three operators.

  • The unary operator operates on a single operation object (such as-). The unary operator is divided into the prefix and the Postfix operator. The prefix operator must be placed before the operation object (such! B). The post operator must follow the operation object (for example, I ++ ).
  • Binary operators operate on two operation objects (such as 2 + 3), which are left in the middle because they appear between the two operation objects.
  • Three-element operators operate on three operation objects. Like C, SWIFT only has one three-element operator, that is, the three-element conditional operator (? B: C ).


The value affected by the operator is called the operand. In expression 1 + 2, the plus sign + is a binary operator, and its two operands are values 1 and 2.

Value assignment operator

Value assignment (a = B) indicates that the value of B is used to initialize or update the value of:

  1. Let B = 10
  2. VaR A = 5
  3. A = B
  4. // A is now 10

If the right side of the assignment is a multivariate group, its elements can be immediately decomposed into multiple variables or variables:

  1. Let (x, y) = (1, 2) // now X equals 1, Y equals 2

Unlike C and objective-C, Swift does not return any value for the value assignment operation. The following code is incorrect:

  1. If X = y {
  2. // This sentence is incorrect because X = y does not return any value
  3. }

This feature prevents you from writing (=) errors as (=). Because if x = y is an error code, swift helps you avoid these code errors from the underlying layer.

Numeric operation

Swift allows all numeric types to support the basic four arithmetic operations:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  1. 1 + 2 // equal to 3
  2. 5-3 // equal to 2
  3. 2*3 // 6
  4. 10.0/2.5 // 4.0

Unlike C and objective-C, Swift does not allow overflow in numeric operations by default. However, you can use the swift overflow operator to overflow your purpose (for example, a & + B ). For more information, see overflow operators.

Addition operators are also used for String concatenation:

  1. "Hello," + "world" // equals to "Hello, world"

Two character values or a string and a character value are added to generate a new string value:

  1. Let dog: character = "D"
  2. Let cow: character = "C"
  3. Let dogcow = dog + cow
  4. // Note: the original quotation marks are cute puppies and mavericks, but the expression characters are not supported in win OS, so they are changed to common characters.
  5. // Dogcow is now "DC"

For more information, see concatenate character strings.

Remainder operation

The result of the remainder operation (A % B) is the number of times that B can be added to a. The remainder is returned ).

Note: The remainder operation (%) is also called the modulo operation in other languages. Strictly speaking, however, the result of the negative number operation of this operator is more suitable for "remainder" than "modulo.

Let's talk about how to get the remainder. Calculate 9% 4. First, you can calculate the number of times of 4, which can be added to 9:

2 times, very good. The remainder is 1 (marked in orange)

In swift:

  1. 9% 4 // equal to 1

To get the result of a % B, % calculates the following equation and outputs the remainder as the result:
A = (B x multiple) + Remainder
When the number of multiples is the maximum value, it can be incorporated into.

Let's replace 9 and 4 into the equations. We get 1:

  1. 9 = (4 × 2) + 1

In the same way, we will calculate-9% 4:

  1. -9% 4 // equal to-1

Place-9 and 4 into the equation.-2 is the maximum integer obtained:

  1. -9 = (4 x-2) +-1

The remainder is-1.

When the remainder of Negative B is calculated, the symbol of B is ignored. This means that the results of a % B and A %-B are the same.

Floating Point Number remainder Calculation

Unlike C and objective-C, Swift can perform remainder on floating point numbers.

  1. 8% 2.5 // equal to 0.5

In this example, except for 2.5, 8 equals 3 to 0.5, so the result is a double value of 0.5.

Auto-increment and auto-increment operations

Like the C language, swift also provides operators that facilitate the addition of 1 or the subtraction of 1 to the variable itself. The operation objects can be integer and floating point. Bytes

  1. VaR I = 0
  2. ++ I // now I = 1

Each time you call ++ I, the value of I is increased by 1. In fact, ++ I is short for I = I + 1, and -- I is short for I = I-1.

++ And -- both pre-and post-operations. ++ I, I ++, -- I and I -- are both effective methods.

Note that these operators modify I and return a value. If you only want to modify the value of I, you can ignore the returned value. However, if you want to use the return value, you need to note that the values returned by the Pre-and Post-operations are different.

  • When ++ is prefixed, it is returned after the auto-increment operation.
  • When ++ is followed, the system returns the result before auto-increment.


For example:

  1. VaR a = 0
  2. Let B = ++ A // A and B are both 1
  3. Let C = A ++ // A is now 2, but C is the value 1 before a auto-increment.

In the preceding example, let B = ++ A adds A1 first and then returns the value of. So both A and B are new values of 1.

Let C = A ++ returns the value of a first, and then adds 1 to. Therefore, C obtains the old value of a 1, and the value of a after adding 1 becomes 2.

Unless you need to use the I ++ features, we recommend that you use ++ I and -- I, because the first modification and then the return of such behavior are more in line with our logic.

One dollar negative number

You can use the prefix-(mona1 negative) to switch between positive and negative numbers:

  1. Let three = 3
  2. Let minusthree =-three // minusthree is equal to-3
  3. Let plusthree =-minusthree // plusthree is equal to 3, or "negative 3"

A mona1 negative sign (-) is written before the operand, with no space in the middle.

Mona1 normal number

Returns the value of the operand without any change.

  1. Let minussix =-6
  2. Let alsominussix = + minussix // alsominussix equals to-6

Although one dollar + is useless, when you use a negative number to express a negative number, you can use a positive number to express a positive number, so your code will be symmetric.

Compound assignment operators)

Like the powerful C language, swift also provides a composite value assignment operator that combines other operators and value assignment operations (=). The addition operation (+ =) is one example:

  1. VaR A = 1
  2. A + = 2 // A is now 3

Expression A + = 2 is short for expression A = a + 2. An addition operation completes the addition and assignment.

Note: The compound assignment operation does not return values. Let B = a + = 2 is an error. This is different from the auto-increment and auto-subtraction operators mentioned above.

The expression section contains a complete list of compound operators. Bytes

Comparison

Comparison operations in all standard C languages can be used in swift.

  • Equal to (a = B)
  • Not equal to (! = B)
  • Greater than (A> B)
  • Less than (a <B)
  • Greater than or equal to (A> = B)
  • Less than or equal to (a <= B)
Note: swift also provides constant equal = and non-constant! = These two comparison operators are used to determine whether two objects reference the same object instance. More details are in the class and structure.

Each comparison operation returns a Boolean value indicating whether the expression is true:

  1. 1 = 1 // true, because 1 is equal to 1
  2. 2! = 1 // true, because 2 is not equal to 1
  3. 2> 1 // true, because 2 is greater than 1
  4. 1 <2 // true, because 1 is less than 2
  5. 1> = 1 // true, because 1 is greater than or equal to 1
  6. 2 <= 1 // false, because 2 is not less than or equal to 1

Comparison operations are mostly used for conditional statements, such as if conditions:

  1. Let name = "world"
  2. If name = "world "{
  3. Println ("Hello, world ")
  4. } Else {
  5. Println ("I'm sorry \ (name), but I don't recognize you ")
  6. }
  7. // Output "Hello, world", because 'name' is equal to "world"

For the if statement, see control flow.

Ternary conditional Operator)

The special feature of the ternary conditional operation is that it has three operands, and its prototype is a problem? Answer 1: Answer 2. It is a concise expression of the Two-choice operations based on whether the problem is true or not. If the question is true, the result of answer 1 is returned. If not, the result of answer 2 is returned.
The following code is simplified by using the ternary conditional operation:

  1. If Question :{
  2. Answer1
  3. }
  4. Else {
  5. Answer2
  6. }

Here is an example of computing table rows. If there is a header, the row height should be 50 pixels higher than the content height; if there is no header, only 20 pixels higher.

  1. Let contentheight = 40
  2. Let hasheader = true
  3. Let rowheight = contentheight + (hasheader? 50: 20)
  4. // Rowheight is 90 now

In this way, the write is simpler than the following code:

  1. Let contentheight = 40
  2. Let hasheader = true
  3. VaR rowheight = contentheight
  4. If hasheader {
  5. Rowheight = rowheight + 50
  6. } Else {
  7. Rowheight = rowheight + 20
  8. }
  9. // Rowheight is 90 now

The first code example uses a three-element conditional operation, so a line of code can give us a correct answer. This is much simpler than the second code. You do not need to define rowheight as a variable because its value does not need to be changed in the IF statement.
Conditional operations provide an efficient and convenient way to express two-choice. You need to pay attention to the fact that over-using ternary conditional operations will change from concise code to obscure code. We should avoid using multiple ternary conditional operators in a combined statement.

Interval Operators

Swift provides two operators to easily express the value of a range.

Closed Interval Operator

The closed interval operator (a... B) defines a range that contains all values from A to B (including a and B. The distinct closed interval operator is very useful when all values in a specific interval are iterated, for example, in a for-in loop:

  1. For index in 1... 5 {
  2. Println ("\ (INDEX) * 5 = \ (Index * 5 )")
  3. }
  4. // 1*5 = 5
  5. // 2*5 = 10
  6. // 3*5 = 15
  7. // 4*5 = 20
  8. // 5*5 = 25

For more information about for-in, see control flow.

Semi-closed interval

A semi-closed interval (A. B) defines a range from A to B, but does not include B. This is called a semi-closed interval because it contains the first value instead of the last value.

The practicality of the semi-closed interval is that when you use a list starting from 0 (such as an array), it is very convenient to count from 0 to the length of the list.

  1. Let names = ["Anna", "Alex", "Brian", "Jack"]
  2. Let COUNT = names. Count
  3. For I in 0 .. count {
  4. Println ("the \ (I + 1) Name \ (Names [I])")
  5. }
  6. // 1st people are Anna
  7. // 2nd calls Alex
  8. // The name of 3rd is Brian.
  9. // 4th People Are Jack

The array has four elements, but 0 .. count is counted only to 3 (the subscript of the last element), because it is a semi-closed interval. For more information about arrays, see arrays.

Logical operation

The operation object of logical operations is a logical Boolean value. Swift supports three standard logical operations based on the C language.

  • Non-logical (! A)
  • Logic and (A & B)
  • Logic or (a | B)
Non-logical

Logical non-operation (! A) returns the inverse of a Boolean value to make true false or false true.

It is a prefix operator that must appear before the operand without spaces. Read as non-A, and then let's look at the following example:

  1. Let allowedentry = false
  2. If! Allowedentry {
  3. Println ("Access Denied ")
  4. }
  5. // Output "Access Denied"

If! The allowedentry statement can be read as "if it is not a alowed entry. ", The next line of code is executed only when" non-allow entry "is true, that is, allowentry is false.

In the sample code, careful selection of Boolean constants or variables helps code readability and avoids the use of double logical non-computation or chaotic logical statements.

Logic and

Logic and (A & B) indicate that the value of the entire expression is true only when the values of A and B are both true.

If any value is false, the value of the entire expression is false. In fact, if the first value is false, the second value is not calculated because it cannot affect the results of the entire expression. This is called "short-circuit evaluation )".

In the following example, access is allowed only when both bool values are true:

  1. Let entereddoorcode = true
  2. Let passedretinascan = false
  3. If entereddoorcode & passedretinascan {
  4. Println ("Welcome! ")
  5. } Else {
  6. Println ("Access Denied ")
  7. }
  8. // Output "Access Denied"
Logic or

Logical or (a | B) is a center operator consisting of two consecutive |. It indicates that one of the two logical expressions is true, and the entire expression is true.

Similar to logic and operation, the logic is also short-circuit calculation. When the expression on the left side is true, the expression on the right is not calculated, because it cannot change the value of the entire expression.

In the following sample code, the first Boolean value (hasdoorkey) is false, but the second value (knowsoverridepassword) is true. Therefore, the entire expression is true, so access is allowed:

  1. Let hasdoorkey = false
  2. Let knowsoverridepassword = true
  3. If hasdoorkey | knowsoverridepassword {
  4. Println ("Welcome! ")
  5. } Else {
  6. Println ("Access Denied ")
  7. }
  8. // Output "Welcome! "
Combination Logic

We can combine multiple logical operations to express a compound logic:

  1. If entereddoorcode & passedretinascan | hasdoorkey | knowsoverridepassword {
  2. Println ("Welcome! ")
  3. } Else {
  4. Println ("Access Denied ")
  5. }
  6. // Output "Welcome! "

This example uses a Composite Logic containing multiple & |. But in any case, & and | can only operate on two values. Therefore, this is actually the result of three simple logical continuous operations. Let's explain:

If we enter the correct password and pass the retina scan, or we have a valid key, or we know the password reset in an emergency, we can open the door.

The first two cases are not met, so the result of the first two simple logic is false, but we know the password reset in an emergency, therefore, the value of the entire complex expression is true.

Use parentheses to specify priority

To make a complex expression easier to understand, it is very effective to use parentheses to specify the priority, although it is not necessary. In the previous example about the door permission, we added a bracket to the first part to use it to make the logic clearer:

  1. If (entereddoorcode & passedretinascan) | hasdoorkey | knowsoverridepassword {
  2. Println ("Welcome! ")
  3. } Else {
  4. Println ("Access Denied ")
  5. }
  6. // Output "Welcome! "

These parentheses make the first two values an independent part of the entire logical expression. Although the output results with and without parentheses are the same, the Code with parentheses is clearer for those who read the code. Readability is more important than simplicity. Please add parentheses where your code becomes clearer!

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.