4. Swift tutorial translation series-Basic Swift Operators

Source: Internet
Author: User

English region http: // download.csdn.net/detail/tsingheng/7480427

An operator is a special symbol that can be used for viewing, changing, or adding values. For example, the addition operator + can add two numbers. There are also some complex examples such as logic and & or auto-increment ++. Swift supports most operators in C and adds some enhanced features to reduce errors in code. The value assignment budget operator = does not return values. This avoids misuse of = where the comparison operator = should be used. Mathematical operators (addition, subtraction, multiplication, division, and modulo) will make overflow judgments, so as to avoid the strange phenomenon of value overflow. You can use the overflow operation provided by Swift to allow overflow, which will be introduced later.

Swift floating point can be used for modulo calculation, but C cannot. Swift also provides range symbols (1 .. 4 and 4 .. 6 ).

This article introduces some common operators. Special operators are introduced in the special Swift operators. They also introduce how to use custom operators or perform operator operations for custom classes.

1. Terms

The operator can be one, two, or three.

  • The unary operator operates only on a single value. Unary operators are usually closely related to the Operation object.
  • Binary operators operate on image values. It usually appears in the middle of two operation objects.
  • The ternary operator involves three objects, and the Swift language only has one ternary operator. (? B: c) no doubt.

The value affected by the operator is called the operation element. For expression 1 + 2, the plus sign (+) is a binary operator, and its two operators are 1 and 2 respectively.

Value assignment operator

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

let b = 10var a = 5a = b// a is now equal to 10
If the value assignment operator is a tuple on the right, the values in the tuples can be parsed and assigned to multiple variables or constants at a time.

let (x, y) = (1, 2)// x is equal to 1, and y is equal to 2
Unlike C or OC assignment, Swift assignment does not return values. This is wrong as follows:

if x = y {    // this is not valid, because x = y does not return a value}
This feature prevents = from being used. If x = y is reported by the compiler, you can avoid such errors.

2. mathematical operators

Swift provides four standard mathematical operators to support multiple numeric types. Addition, subtraction, multiplication, division

1 + 2       // equals 35 - 3       // equals 22 * 3       // equals 610.0 / 2.5  // equals 4.0
However, by default, Swift mathematical operators cannot overflow. You can use the overflow operator to allow overflow, for example, a & + B;

The plus sign operator can also be used to connect strings such as "hello," + "china". The result is "hello, china ". Two characters, or one character, can be added to a string. (In the following example, the characters are emoticon. It should not be supported by windows, 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) means a = n * B + c, n is an integer, c is smaller than B, and c is the result.

NOTE: I would like to think about the remainder operation and the modulo operation in other languages. However, in Swift, the remainder operation can still be a negative number, so it is still called the remainder operation.

Here is an illustration showing how to find the remainder. To compute 9% 4, you must first calculate the number of 4 in 9:

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


You can put 2 4 in 9, and the rest is 1.

To calculate the result of a % B, formula a = (B * someMultiplier) + remainder is used and remainder is used as the return value. SomeMultiplier is the maximum number of B that can be accommodated in a. The example above is 9 = (4*2) + 1.

The same method is used when a is a negative number. -9% 4 is equal to-1. The substitution formula is-9 = (4 *-2) + (-1). The result is-1. If B is a negative number, the negative numbers of B are ignored, so the results of a % B and a %-B are always the same.

Floating Point Number remainder operation

The Swift remainder operation can also be used for floating point numbers. For example, the result of 8% 2.5 is 0.5. It's too simple to translate these sentences.

Auto-increment and auto-increment Operators

Like C, Swift provides the auto-increment (++) and auto-increment (--) operators to conveniently add or subtract 1 to a value. These two operators can be used for integers or floating-point numbers.

Var I = 0 ++ I // I is equal to 1

Each time you call ++ I, the value of I is increased by 1. ++ I is actually the abbreviation of I = I + 1. In the same way, I is the abbreviation of I = I-1.

++ And -- can both be used as prefixes and suffixes, ++ I and I ++ are both correct, and -- I and I -- are also correct (are you still using them, it's the same as laruence)

Note that the two operators both modify the I value and return a value. If you just want to change the I value, you can ignore the final return value, but when you want to use the return value, pay attention to the difference between the prefix and the suffix. If the prefix is used, the value before 1 is returned, and the value after 1 is returned using the suffix. For example

var a = 0let b = ++a// a and b are now both equal to 1let c = a++// a is now equal to 2, but c has been set to the pre-increment value of 1
In the preceding example, let B = ++ a first adds 1 to the value of a and then returns the value of. This explains why the values of a and B are both 1. But let c = a ++ returns the value of a before adding 1 to. So after this is done, a is 2, and c is 1.

We recommend that you use ++ I and -- I as much as possible. I write I ++ in JAVA.

Unary negative operator

You can use-to change the symbol of a number.-It is a unary operator.

let three = 3let minusThree = -three       // minusThree equals -3let plusThree = -minusThree   // plusThree equals 3, or "minus minus three”
-Directly put it in front of the operation object without any spaces in the middle.

Unary positive operator

The + operator only returns the value of the operation object without any changes.

let minusSix = -6let alsoMinusSix = +minusSix  // alsoMinusSix equals -6
Although the plus sign is a good change, if you add a negative number to the Code, adding a positive number to the positive number is more symmetrical.

Compound value assignment

Swift also provides compound assignment operations to combine assignment operators with other operators. A typical example is + =.

var a = 1a += 2// a is now equal to 3
A + = 2 is the abbreviation of a = a + 2. The two methods are the first to combine the two operators, and the execution time is the same.

NOTE compound operators do not return values. For example, let B = a + = 2 cannot be used. This is different from the auto-increment auto-subtraction operation.

3. Comparison Operators

Swift supports all comparison operators in C. Comparison is equal, 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 the reference of two objects or the reference of the same object.

The return value of each comparison operator is Bool, indicating whether the expression is correct.

1 == 1   // true, because 1 is equal to 12 != 1   // true, because 2 is not equal to 12 > 1    // true, because 2 is greater than 11 < 2    // true, because 1 is less than 21 >= 1   // true, because 1 is greater than or equal to 12 <= 1   // false, because 2 is not less than or equal to 1
Comparison operators are usually used in conditional statements, such as if statements.

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 that consists of three parts in the form of question? Answer1: answer2. The following expression is calculated based on whether the question condition is true or false. If question is true, answer1 is calculated and answer1 is returned. If it is false, answer2 is returned. The Code is as follows:

if question {    answer1} else {    answer2}
The following example calculates the height of a table row. If a table has a header, the row height is 50px higher than the content. If there is no header, the row height is 20px higher than the content:

let contentHeight = 40let hasHeader = truelet rowHeight = contentHeight + (hasHeader ? 50 : 20)// rowHeight is equal to 90
This is the case if

let contentHeight = 40let hasHeader = truevar rowHeight = contentHeightif hasHeader {    rowHeight = rowHeight + 50} else {    rowHeight = rowHeight + 20}// rowHeight is equal to 90
If you use the ternary operator, set the line height to only one line of code. It is much more than the introduction of using if. You do not need to define rowHeight as a variable, because you do not need to change the value of rowHeight in if.

The ternary operator provides an efficient way to express either of the two conditions. However, when using the ternary operator, you should also note that if it is too concise, it may reduce the readability of the Code. Avoid combining multiple ternary operators into a statement.

5. Range Operators

Swift provides two range operators to indicate the value range.

Closed range Operator

The closed range operator (a... B) defines the range from a to B and contains a and B. When you want to traverse a range and use each value in the range, you can use the range operator, such as the 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 Operator

The semi-closed range operator (a. B) defines the range from a to B that contains a but does not contain B. It is called the semi-closed range operator because only the left side does not contain the right boundary.

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

let names = ["Anna", "Alex", "Brian", "Jack"]let count = names.countfor 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 contains four items, but 0 .. count only contains three items.

6. logical operators

Logical operators can be modified or combined with logical values true and false. Swift supports three standard logical operators: Non (!), And (&), or (|)

Logical non-Operator

Logical non-operators take the opposite result, so true becomes false, and flase becomes true. Logical non-operators are prefix operators, and spaces are not allowed between them and the operation objects. Can be read as "not"

let allowedEntry = falseif !allowedEntry {    println("ACCESS DENIED")}// prints "ACCESS DENIED"
Expression if! AllowedEntry can be read as "if it is not allowed to enter". if the code in it can be executed only when it is not allowed to enter the real state, that is, if it is allowed to enter the false state.

Just like in this example, getting a good name for a Boolean variable or constant keeps the code clean and easy to read, and avoiding double negatives or confusing expressions.

Logic and operators

For logical and (a & B) operators, true is returned only when both a and B are true. Otherwise, false is returned. If either a or B is false, the entire expression is false. In fact, if a is false, B will not calculate it again, because it is unnecessary. In the following example, two bool values are used, and welcome can be output only when both values are true.

let enteredDoorCode = truelet passedRetinaScan = falseif enteredDoorCode && passedRetinaScan {    println("Welcome!")} else {    println("ACCESS DENIED")}// prints "ACCESS DENIED”

Logic or operator

For logic or (a | B), as long as a and B have a true value, the result is true. Like logic, if the calculation result of a is true, the system will not directly return true if the value of B is calculated. In the following example, A Bool value is false, but the second value is true. The two values are still true after calculation, so if

let hasDoorKey = falselet knowsOverridePassword = trueif hasDoorKey || knowsOverridePassword {    println("Welcome!")} else {    println("ACCESS DENIED")}// prints "Welcome!”
Combined with logical operations

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

if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {    println("Welcome!")} else {    println("ACCESS DENIED")}// prints "Welcome!”
The preceding example uses multiple & | to form a long compound expression. However, & | can only calculate two values respectively. Therefore, three statements are actually connected together and can be interpreted:

If we have already entered the correct door and passed the retina scan, or if we have a legitimate door card, or if we know the password to lift the emergency alert, then we can enter.

Through the calculation of values enteredDoorCode, passedRetinaScan, and hasDoorKey, the calculation results of the first two expressions are false. However, we know the password for unlocking the alarm status. Therefore, the result of the entire expression is true.

7. Explicit brackets

Sometimes parentheses can be used or not used in some places, but the brackets can make the Code look clearer. As in the above example, adding parentheses to the first part is very useful, and the intent of the code is very clear.

if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {    println("Welcome!")} else {    println("ACCESS DENIED")}// prints "Welcome!”
Parentheses indicate that the first result is an independent part of the overall result. Adding parentheses does not affect the expression calculation result, but the overall intention is clearer and easier to read. Readability is always more important than simplicity. Use parentheses whenever possible.

This chapter is complete. Chapter 5. Swift strings and characters

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.