iOS development Language Swift entry---basic operators

Source: Internet
Author: User

An operator is a special symbol or phrase that examines, alters, and merges values. For example, a plus + adds two numbers (such as let i = 1 + 2). Complex operations such as logic and operator && (such as if Entereddoorcode && passedretinascan), or a handy increment operator ++i such as the I value plus 1.
Supports most of the standard C language operators and improves many features to reduce general coding errors. Such as: the assignment (=) does not return a value to prevent errors caused by assigning an assignment to the place where you want to determine the equality operator (= =). The numeric operator (+,-, *,/,%, and so on) detects that the value overflow is not allowed, to avoid the exception result when the variable is saved because the variable is greater than or less than the range that its type can carry. Of course it allows you to use Swift's overflow operator to implement overflow. See overflow operator for details.
Unlike the C language, in Swift you can take the floating-point count (%), and Swift also provides the C language without the interval operator that expresses the value between two numbers (a.). B and A...B), which facilitates us to express values within a range.
This section describes only the basic operators in Swift, the advanced operators contain advanced operators, how to customize operators, and how to perform operator overloading of custom types.
  

Terms

Operators have unary, two, and ternary operators.
Unary operators operate on single-action objects, such as-a. Unary operators are pre-and post-operators, and the predecessor operator is preceded by an operand (such as!b), and the post operator is immediately followed by the operand (such as i++).
The binary operator operates on two operand objects (such as 2 + 3), which are central because they appear between the two operand objects.
The ternary operator operates on three operands, just like the C language, Swift has only one ternary operator, which is the ternary conditional operator (a? B:C).
The value affected by the operator is called the operand, in expression 1 + 2, plus + is the two-tuple operator, and its two operands are the values 1 and 2.
  

Assignment operators

An assignment operation (a = B) that represents the value of B to initialize or update the value of a:

let10var5a = b// a 现在等于 10

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

let (x, y) = (12)// 现在 x 等于 1, y 等于 2

Unlike the C language and Objective-c, Swift's assignment does not return any value. So the following code is wrong:

if x = y {    // 此句错误, 因为 x = y 并不返回任何值}

This feature makes it impossible to write (= =) incorrectly (=), because if x = y is the error code, Swift helps you avoid these error codes from the bottom.
  

Numeric operations

The basic arithmetic is supported for all numeric types in:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)

12       // 等于 353       // 等于 223       // 等于 610.02.5  // 等于 4.0

Unlike the C language and objective-c, Swift defaults to not allowing overflow in numeric operations. But you can use Swift's overflow operator to reach your purposeful overflow (such as a &+ b). See overflow operator for details.
The addition operator can also be used for concatenation of strings:

"hello, ""world"  "hello, world"

Two character values or a string and a character value, the addition generates a new string value:

let"d"let"c"let dogCow = dog + cow// 译者注: 原来的引号内是很可爱的小狗和小牛, 但win os下不支持表情字符, 所以改成了普通字符// dogCow 现在是 "dc"

See the concatenation of characters and strings for details.
  

To find the remainder operation

The remainder operation (a% B) is the number of times B is just good enough to be able to accommodate a, returning the extra portion of the part.
Attention:
The remainder operation (%) is also called modulo operation in other languages. Strictly speaking, however, we look at the result of the operator's operation on negative numbers, and the "redundancy" is more appropriate than "modulo".
Let's talk about how to get the remainder, calculate 9 4, you first calculate how many times 4 will fit into the 9:

Twice times, very good, that remainder is 1 (marked in orange)
In Swift, this is the expression:

94    // 等于 1

In order to get the result of a% B,% calculates the following equation and outputs the remainder as a result:
x multiple) + remainder
When the multiplier takes the maximum value, it will just fit into a.
Put 9 and 4 into the equation, we have 1:

9 = (4 × 2) + 1

The same method that I came to calculate-9 4:

-94   // 等于 -1

Put 9 and 4 into the equation, 2 is the largest integer taken:

-9 = (4 × -2) + -1

The remainder is-1.
When a negative number B is remainder, the b symbol is ignored. This means that the results of a% B and a%-B are the same.
Calculation of floating-point number for remainder
Unlike the C language and objective-c,swift, floating-point numbers can be redundant.

82.5// 等于 0.5

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

Self-increment and self-increment operations

Like the C language, Swift also provides an operator that facilitates self-increment (+ +) and decrement (–) by adding 1 or minus 1 to the variable itself. Its operands can be shaped and floating-point.

var0++i      // 现在 i = 1

Each time ++i is called, the value of I is added 1. In fact, ++i is shorthand for i = i + 1, while –i is shorthand for i = i-1.
+ + and – both pre-and post-op. ++i, i++, –i and I – are all valid formulations.
It is important to note that these operators have a return value after I have modified I. If you only want to modify the value of I, then you can ignore the return value. But if you want to use the return value, you need to be aware that the return value of the pre-and post-operation is different.
When + + is pre-set, the first self-build and return.
When the + + is back-up, return to the self-increment first.
For example:

a0let b = ++a //a1aa2a1

In the example above, let B = ++a first adds 1 and then returns the value of a. So both A and B are the new value 1.
While let C = a++, the value of a is returned first, then a is added 1. So C gets the old value of a 1, and a plus 1 turns 2.
Unless you need to use i++ 's features, it is recommended that you use ++i and –i, because it is more consistent with our logic to return such behavior before modifying it.
 

unary minus

The sign of a value can be toggled using a prefix-(that is, a unary minus):

let=3let=-three       // minusThree 等于 -3let=-minusThree   // plusThree 等于 3, 或 "负负3"

A unary minus (-) is written before the operand with no spaces in the middle.
  

Unary Plus

Unary plus (+) returns the value of the operand without any change.

let minusSix = -6let alsoMinusSix = +minusSix  // alsoMinusSix 等于 -6

Although unary + does not work hard, when you use a unary minus to express negative numbers, you can use a unary plus to express positive numbers, so your code will have symmetrical beauty.
Compound assignment (Compound assignment Operators)
Like the powerful C language, Swift also provides a compound assignment operator that combines other operators and assignment operations (=), an example of which is an add-on operation (+ =):

a1a2 // a 现在是 3

The expression A + = 2 is a shorthand for a = a + 2, and an add-and-assign operation completes the addition and assignment of two things.
Attention:
Compound assignment operation has no return value, let B = a + = 2 Such code is an error. This differs from the self-increment and decrement operators mentioned above.
There is a complete list of composite operators in the expression section.
  

Comparison operation

Comparison operations in all standard C languages can be used in Swift.
equals (A = = b)
Not equal to (a! = b)
Greater than (a > B)
Less than (a < b)
Greater than or equal to (a >= b)
Less than or equal to (a <= b)
Attention:
The two comparators, identity = = = and non-identical!==, are also provided to determine whether two objects refer to the same object instance. More details in the class with the structure.
Each comparison operation returns a Boolean value that identifies whether the expression is true:

1==1//trueBecause1Equals12!=1//trueBecause2Not equal to12>1//trueBecause2Greater than11<2//trueBecause1Less than21>=1//trueBecause1Greater than or equal12<=1//falseBecause2is not less than or equal1

Comparison operations are used for conditional statements, such as the IF condition:

"world"if"world" {    println("hello, world"else {    println("I‘m sorry \(name), but I don‘t recognize you""hello, world"`name` "world"

For the IF statement, see Control flow.
  

Ternary conditional operations

The ternary conditional operation is special because it is an operator with three operands, and its prototype is a problem? Answer 1: Answer 2. It succinctly expresses the operation based on the question of whether or not to make two choices. If the problem is true, return the result of answer 1, or if not, return the result of answer 2.
The following code is simplified using the ternary conditional operation:

if{  answer1}else{  answer2}

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

let40lettruelet5020)// rowHeight 现在是 90

This will be simpler than the following code:

let40lettruevar rowHeight = contentHeightif hasHeader {    50else {    20}// rowHeight 现在是 90

The first code example uses ternary conditional operations, so a single line of code allows us to get the correct answer. This is much simpler than the second code, without having to define rowheight as a variable, because its value does not have to be changed in the IF statement.
Ternary conditional operations provide an efficient and convenient way to express the choice of two choices. It is important to note that over-use ternary conditional operations can be made into hard-to-understand code by simple code. We should avoid using multiple ternary conditional operators in a combined statement.
  

Interval operator

Provides two operators that facilitate the expression of a range of values.
  closed interval operator
The Closed interval operator (A...B) defines an interval that contains all values from A to B (including A and b). The closed interval operator is useful when iterating through all the values of an interval, such as in a for-in loop:

forin1...5 {    println("\(index) * 5 = \(index * 5)")}// 1 * 5 = 5// 2 * 5 = 10// 3 * 5 = 15// 4 * 5 = 20// 5 * 5 = 25

For for-in, see control flow.
  semi-closed interval
Semi-closed interval (a). b) define a range from A to B but not including B. This is called a semi-closed interval because the interval contains the first value and not the last value.
The practicality of semi-closed intervals is that when you use a 0-based list (such as an array), it is very convenient to count from 0 to the length of the list.

let names = ["Anna""Alex""Brian""Jack"]let count = names.countforin0..count {    println("第 \(i + 1) 个人叫 \(names[i])")}// 第 1 个人叫 Anna// 第 2 个人叫 Alex// 第 3 个人叫 Brian// 第 4 个人叫 Jack

The array has 4 elements, but 0: Count only counts to 3 (the subscript of the last element) because it is a semi-closed interval. For an array, consult the array.
  

Logical operations

The operand of a logical operation is a logical Boolean value. Swift supports three standard logic operations based on the C language.
Logical non (!A)
Logic with (a && b)
Logic or (A | | b)
Logical Non-
The logical non-operation (!a) deserializes a Boolean value so that true becomes false and false to true.
It is a predecessor operator that needs to appear before the operand without spaces. Read as non-A, then we look at the following example:

letfalseif !allowedEntry {    println("ACCESS DENIED""ACCESS DENIED"

The IF!allowedentry statement can be read as "If non-alowed entry. ", the next line of code is executed only if" non-Allow entry "is true, that is, Allowentry is false.
In the sample code, careful selection of Boolean constants or variables is helpful to the readability of the code and avoids the use of double logical non-operations, or chaotic logical statements.
  Logic and
Logic with (a && b) expresses that the value of the entire expression is true when only the values of A and B are true.
As long as any one value is false, the value of the entire expression is false. In fact, if the first value is false, then the second value is not evaluated because it is not possible to affect the result of the entire expression. This is called "Short circuit calculation (short-circuit evaluation)".
In the following example, only two bool values are allowed to enter when the value is true:

lettrueletfalseif enteredDoorCode && passedRetinaScan {    println("Welcome!"else {    println("ACCESS DENIED""ACCESS DENIED"

  Logical OR
Logic or (A | | b) is a by two consecutive | The middle operator that is composed. It indicates that one of the two logical expressions is true, and the entire expression is true.
Similar to logic and operation, logic or "short-circuit calculation", when the left-hand expression is true, the right expression is not evaluated because it is not possible to 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, so the entire expression is true, allowing access:

letfalselettrueif hasDoorKey || knowsOverridePassword {    println("Welcome!"else {    println("ACCESS DENIED""Welcome!"

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

if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {    println("Welcome!"else {    println("ACCESS DENIED")}// 输出 "Welcome!"

This example uses a number of && and | | Compound logic. But no matter how,&& and | | Only two values can be manipulated at all times. So this is actually the result of three simple logical sequential operations. Let's take a look at:
If we enter the correct password and pass a retinal scan, or we have a valid key, or we know the password to reset in case of an emergency, we can open the door and enter it.
In the first two cases, we are not satisfied, so the result of the first two simple logic is false, but we are aware of the password reset in case of an emergency, so the value of the entire complex expression is still true.
  

Use parentheses to clarify precedence

For a complex expression to be easier to read, it is very effective to use parentheses in the right place to prioritize, although it is not necessary. In the previous example of permission to a door, we put a parenthesis in the first section, and it looks more logical to use it:

if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {    println("Welcome!"else {    println("ACCESS DENIED")}// 输出 "Welcome!"

This bracket allows the first two values to be seen as a separate part of the entire logical expression. Although the output of parentheses and parentheses is the same, the code with parentheses is clearer for the person reading the code. Readability is more important than brevity, so add a parenthesis to the place where you can make your code clear.

iOS development Language Swift entry---basic operators

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.