# 4.Swift Tutorial Translation series--swift basic operators

Source: Internet
Author: User

The operator refers to a special symbol that can be used to view. Change the value or add it. Let's say the addition operator + can speak two numbers together.

Other complex examples are logic and && or self-increment + +. Swift supports most of the operators in C, and adds some enhanced features to reduce errors in the code. The assignment Budget character = does not return a value. This avoids the need to misuse = in places where the comparison operator = = should be used. Mathematical operators (subtraction modulo) do overflow inference, which avoids strange phenomena that occur when values overflow. You can choose to use the overflow operation provided by Swift to agree to overflow. There will be an introduction at the very back.

Swift floating-point numbers are capable of modulo operations. C is not able to. Swift also offers a range of symbols (1..4 and 4 ... 6).

This is an introduction to some common operators, and special operators are described in the following swift special operators. It also describes how to define an operator or implement an operator for a class you define.

1. Terminology

The operator can be a unary, two, or ternary.

• A unary operator operates on only a single value. Unary operators usually cling to this operand. Both before and after.

• The binary operator operates on a value like this. Generally, there are now two operands in the middle of the object.
• The ternary operator involves three objects, and the swift language has only one ternary operator. (a? b:c) no doubt.

The value that the operator affects is called an operand.

For an expression 1+2. The plus sign (+) is a two-dollar operator whose two operands are 1 and 2 respectively.

Assignment operators

The assignment operator (a = b) uses the value of B to initialize or update the value of a.

```let b = 10
var a = 5
a = b
// a is now equal to 10

```
Assuming that the right side of the assignment operator is a tuple, the values in the tuple can be parsed once and assigned to multiple variables or constants.

```Let (x, y) = (1, 2)//x is equal to 1, and y are equal to 2
```
Unlike the assignment of C or OC, the assignment operation of Swift does not return a value. Like the following, it's wrong.

```If x = y {    //This isn't valid, because x = y does not return a value}
```
This feature prevents the use of the = = in place. The compiler has an error with the If x= y. You can avoid this kind of mistake.

2. Mathematical operators

Swift provides four standard mathematical operators to support multiple numeric types.

Subtraction

```1 + 2       // equals 3
5 - 3       // equals 2
2 * 3       // equals 6
10.0 / 2.5  // equals 4.0

```
However, by default, the Swift math operator does not agree to overflow.

You can agree to overflow by overflow operator For example a &+ b;

The plus operator can also be used to concatenate strings such as "Hello," + "China" and the result is "Hello,china". Two characters, or a character followed by a string, can be added to the string. (The following example characters with an emoticon, not Windows should not support it, I guess.) ）

```let dog: Character = "d"
let cow: Character = "c"
let dogCow = dog + cow
// dogCow is equal to "dc”

```
Remainder operator

The remainder operation (a% B) refers to A = N*b+c. n is an integer, C is smaller than B, and C is the result.

NOTE the remainder operation and the other language inside the modulo operation very much wanted. However, swift inside the balance can also be negative, so it is called to find the remainder operation.

Here's a diagram showing how to find out what's going on. Increase to calculate 9%4. The first thing to calculate 9 is to put a few 4:

 4 4 1 1 2 3 4 5 6 7 8 9

9 can be placed in the next 2 x 4. The rest is 1.

To calculate the result of a a%b, the% operation uses the formula A = (b*somemultiplier) + remainder, and uses remainder as the return value. Somemultiplier is the maximum number of B that can be contained in a. The sample that is brought in is 9 = (4*2) + 1

It's the same way when a is negative.

-9%4 equals-1. The surrogate formula is 9 = (4*-2) + (-1), and the result is-1. Suppose B is a negative number. The minus sign of B will be ignored, so the results of a%b and a%-b are always the same.

Floating-point calculation for remainder

The swift redundancy operation can also be used in floating-point numbers for example, the 8%2.5 result is 0.5.

It is too simple and not good translation of these few explanations will forget.

Self-increment and decrement operators

Just like C. Swift provides the self-increment (+ +) and decrement (--) operators to make it easy to add a value of 1 or minus 1. These two operators can be used for integers or floating-point numbers.

```var i = 0++i//i equals 1.
```

Each time you call ++i, the value of I will be added 1. ++i is actually the abbreviation for i = i+1. The same truth, I = i = i-1 abbreviation.

+ + and--can be used as a prefix or as a suffix. ++i and i++ are right, I and i--are also correct (still use to say, with bird brother as wordy AH)

Note that both operators change the value of I and finally return a value, assuming you just want to change the value of I. The last return value can be ignored, but you should pay attention to the difference between prefix and suffix when you want to use the return value.

Suppose you use a prefix that returns a value up to 1, with a suffix that returns the value after 1. Like what

```var a = 0
let b = ++a
// a and b are now both equal to 1
let c = a++
// a is now equal to 2, but c has been set to the pre-increment value of 1

```
In the example above, let B = ++a first adds 1 to the value of a. The value of a is then returned.

It also explains why the value of A and B is 1.

But let C = a++ Returns the value of a before giving a plus 1. So when this is over, a is 2, and C equals 1.

It is suggested here that as far as possible are ++i and the form of-I, I in Java are written i++ ah.

Unary negative operators

The symbols of numbers can be changed with-. -it's a unary operator.

```let three = 3
let minusThree = -three       // minusThree equals -3
let plusThree = -minusThree   // plusThree equals 3, or "minus minus three”

```
-placed directly in front of the action object. There is no space in the middle.

Unary positive operator

The + operator simply returns the value of the operand, no matter what changes it has.

```let minusSix = -6
let alsoMinusSix = +minusSix  // alsoMinusSix equals -6

```
Although the plus sign is good no matter what changes, but suppose you code to give negative numbers plus minus, give positive home plus number is more symmetrical.

Compound assignment operation

Swift also provides a compound assignment operation. Used to combine assignment operators and other operators. The typical example is the + =

```var a = 1
a += 2
// a is now equal to 3

```
A + = 2 is the abbreviation for a = a+2.

Both methods are just the first to combine two operators together. The run time is the same in both ways.

The NOTE compound operator does not have a return value. Let's say you can't use let B = a+=2.

This is not the same as the self-increment subtraction.

3. Comparison operators

Swift supports all of C's comparison operators, which are more equal. The comparison is not equal, greater than, less than. Greater than or equal to, less than or equal

NOTE Swift also provides two identity comparison operators = = = and. = =, used to compare a reference to a two object or a reference to the same object.

Each of the comparison operator return values is bool, indicating whether the expression is correct.

```1 == 1   // true, because 1 is equal to 1
2 != 1   // true, because 2 is not equal to 1
2 > 1    // true, because 2 is greater than 1
1 < 2    // true, because 1 is less than 2
1 >= 1   // true, because 1 is greater than or equal to 1
2 <= 1   // false, because 2 is not less than or equal to 1

```
The comparison operation wildcard is often used in conditional statements. For example if statement

```let name = "world"
if name == "world" {
println("hello, world")
} else {
println("I'm sorry \(name), but I don't recognize you")
}
// prints "hello, world", because name is indeed equal to "world”

```
4. Ternary conditional Operators

The ternary conditional operator is a special operation, consisting of three parts, in the form of question?

Answer1:answer2. This is based on whether a condition question is true or false determines the subsequent expression. Suppose that question is ture calculates answer1 and returns the result of Answer1, assuming false is answer2. This is what the code says:

```if question {
} else {
}

```
Here's a sample that calculates the height of a table row.

Suppose the table has a header. Higher than the content of 50px, assuming that there is no table header, than the content of 20px higher:

```let contentHeight = 40
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90

```
This is what you write with If.

```let contentHeight = 40
var rowHeight = contentHeight
rowHeight = rowHeight + 50
} else {
rowHeight = rowHeight + 20
}
// rowHeight is equal to 90

```
If you use the ternary operator, you can set the line height to just one line of code. It's more than a simple introduction to the IF in the back. You don't have to define rowheight as a variable. Since there is no need to change the value of RowHeight in the IF.

Ternary operators provide an efficient way to express the case of two choices.

However, when using the ternary operator, it is also important to note that the assumption is too concise and may reduce the readability of the code. Avoid combining multiple ternary operators into a single statement.

5. Scope operators

Swift provides two range operators to represent the range of values

Closed interval range operator

The Closed interval range operator (A...B) defines the range from a to B, and includes A and B. You can use the range operator when you want to traverse a range and need to use every value in the range, such as For-in loop

```for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

```
Semi-closed range operators

Semi-closed range operator (a). b) defines the range from a to B including a but not B, which is called the semi-closed range operator because it only includes the left side excluding the right boundary.

The semi-closed range operator is useful for traversing an array such that the subscript starts from 0 but does not include the length of the array.

```let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..count {
println("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

```
Note that the array consists of four items, but 0. Count is included only to 3.

6. Logical operators

Logical operators can alter or combine logical values of true and false. Swift supports three standard logical operation printable (. ), with (&&), or (| | ）

Logical non-operator

The logical non-operator takes the opposite result, so true becomes false,flase true.

The logical non-operator is the prefix operator and does not agree with a space between the operands.

Can be read as "not a"

```let allowedEntry = false
if !allowedEntry {
}

```
The expression if!allowedentry can be read as "hypothesis is not agreed to enter", if the code only has the assumption that not agree to enter is true when the ability to run. That is, assuming that the consent entered is false.

Just like this example, giving a good name to a Boolean variable or constant keeps the code clean and readable, avoiding double negatives or confusing expressions with some easy ones.

Logic and operators

For logic and (a && b) operators, he returns true only if both A and B are true, otherwise it returns false.

A and b no matter what one is false, the entire expression is false, in fact, suppose A is false,b will not go to calculate, because there is no need ah. The following sample uses two bool values, and only two are true when the ability output welcome

```let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
println("Welcome!")
} else {
}

```

Logical OR operator

For logic or (a | | b) to say. Just A and B have a true, the result is nausea true.

As with logic, assuming that a evaluates to true, the value of B will not be evaluated directly to return true. The following example has a bool value of false, but the second is true, and both are evaluated and true, so if through

```let hasDoorKey = false
println("Welcome!")
} else {
}
// prints "Welcome!”

```
Combining logical operations

You can combine multiple logical operations to form a longer compound statement

```if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
println("Welcome!")
} else {
}
// prints "Welcome!”

```
The above example uses multiple && | | Make up a somewhat long compound expression. But the && | | It is only possible to calculate two values separately, so it is actually three statements that are linked together and can be interpreted as:

Suppose we have entered the right door and passed a retinal scan, or suppose we have a valid door card, or suppose we know the password of the emergency alarm. Then you can enter.

The first two expressions are evaluated as false by calculating the values Entereddoorcode,passedretinascan and Hasdoorkey, but we know the password to dismiss the alert state. So the whole expression result is still true.

7. Understand the parentheses

Sometimes there are places where parentheses can be used without parentheses. But parentheses can make the code look clearer.

Like the example above, the first part of the parentheses is very useful, the code's intentions are very clear

```if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
println("Welcome!")
} else {
}
// prints "Welcome!”

```
The parentheses indicate that the first and the result of the operation is an independent part of the overall result, and that the parentheses do not affect the result of the expression evaluation. But the overall intent became clearer and easier to read. Readability is always more important than brevity.

Use parentheses as much as possible.

The end of this chapter.

Next Chapter Address 5.Swift strings and characters

4.Swift Tutorial Translation series--swift basic operators

Related Keywords:
Related Article

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.