The basic operator of the Swift tutorial _swift

Source: Internet
Author: User
Tags arithmetic arithmetic operators arrays logical operators ranges

An operator is a particular symbol or expression used to examine, modify, or merge variables. For example, with the sum operator + you can sum two digits (such as let i = 1 + 2); a slightly more complex example has logic and operator && (e.g. if Entereddoorcode && Passedretinascan), Self-growth operator ++i (this is the shorthand for i=i+1)

Swift supports most of the operators in the C standard library and promotes their compatibility so that common coding errors can be eliminated. The assignment operator (=) does not return a value, which prevents you from being careless by writing an assignment (=) (=) to make an error. The arithmetic character (+,-, *,/,%, and so on) checks the overflow with the rejected value, which avoids unexpected data when the value type's data exceeds the storage range allowed by the value type. You can choose to use the value overflow operator provided by Swift to quantify the overflow behavior, see the overflow operator in detail.

Unlike the C language, Swift allows you to perform a residual operation on floating-point numbers. At the same time, Swift provides two ranges of operators (a.. B and a...b), as shorthand for a range of values, which C does not support.

This section describes the swift common operators. The advanced operator overrides Swift's advanced operator and describes the implementation of the custom type operator for the custom operator.


Operators are one-yuan, two-yuan or ternary:

A unary operator operates on a single object (such as-a). The unary prefix operator appears before the object (such as!b), and the unary suffix operator appears after the object (such as i++).
The two-dollar operator operates two objects (such as 2 + 3), and the operator is in the middle of two elements.
The ternary operator operates on two objects. Like C, Swift supports only one ternary operator: the ternary conditional operator (a. b:c).

The value that the operator affects is called the operand. Expression 1 + 2, the symbol + is a two-dollar operator and two operands are 1 and 2, respectively.

Assignment operator

The assignment operator (a = b) Initializes or updates A's value with the value of B

Copy Code code as follows:

Let B = 10
var a = 5
A = b
Now the value of a is 10.

If the right assignment data is a tuple of multiple data, its elements can be multiple constants or variables that are assigned at once
Copy Code code as follows:

Let (x, y) = (1, 2)
x equals 1, and y equals 2.

Unlike C and Objective-c, the assignment operator in Swift does not return itself as a value. So the following code is not legal:
Copy Code code as follows:

If x = y {
Error, because x = y does not return a value

This feature helps you avoid errors caused by carelessness in writing (=) the assignment operator (=). This is not valid because if x = y is written in this way.

Mathematical operators
Swift supports four annotation operators for all numeric types:

Addition (+) * Subtraction (-)
Multiplication (*)
Division (/)

For example:

Copy Code code as follows:

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

Unlike C and objective-c, Swift's arithmetic operators do not allow value overruns by default. You can select a value overflow (for example A & + B) by using the swift overflow operator. Refer to Overflow Operators

The addition operator also applies to string concatenation, for example:

Copy Code code as follows:

"Hello," + "world"//equals "Hello, World"

Two characters, or a character string, that can be combined into a new string:
Copy Code code as follows:

Let Dog:character = "dog" (because the browser can not display the dog's Unicode image, so use three letters instead ...)
Let Cow:character = "cow" (ditto ...) )
Let Dogcow = dog + Cow
Dogcow is equal to "Dogcow"

See concatenating Strings and Characters for details.

Fetch operator

The remainder operator (a% b) calculates how several times A is B and returns the left value (remainder).

Note: The remainder operator (%) is also called a modulo operator in other languages. In Swift, however, it means that if the operation of negative numbers is strictly speaking, the remainder is not the modulus.

This is how the remainder operator works. To calculate 9% 4, you first have to find a few times 9 is 4:

9 can remove two 4 and the remainder is 1 (shown in orange).

In Swift, this will be written:

Copy Code code as follows:

9% 4//equals

To determine the answer to a% B, operator% calculates the following equation and returns the remainder as its output:
Copy Code code as follows:

A = (bxsome multiplier) + remainder

Some multiplier is the maximum multiple of B that can be contained in a.

Insert 9 and 4 into the formula:

Copy Code code as follows:

9 = (4x2) + 1

The same method is applied when the remainder of a negative value is computed when a:
Copy Code code as follows:

-9% 4//Equals-1

Insert-9 and 4 into the formula:
Copy Code code as follows:

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

The resulting residual value is-1.

B is omitted when B is negative, which means that the result of%b and%-b is the same.

Floating-point remainder calculation

The remainder operators different from C and objective-c,swift can also be applied to floating-point numbers:

Copy Code code as follows:

8% 2.5//equals 0.5

In this example, 8 with 2.5来 is equal to 3, the remainder is 0.5, so the remainder is 0.5.

Self-increasing and self-subtraction operators

Like C, Swift provides a custom operator (+ +) and a self subtraction operator (–) as a shortcut to increase or decrease a number of 1. You can use these operators for variables of any integer or floating-point type.

Copy Code code as follows:

var i = 0
++i//I now equals 1

Every time you use ++i, the value of I is increased by 1, which in essence ++i can be regarded as i=i+1, as – I can be seen as i=i-1.

The + + and – symbols can be used as prefix operators or as suffix operators. ++i and i++ are two effective ways to increase the value of I by 1, likewise, – I and I-compact.

Note that these operators modify I and return a value. If you only want to add or subtract the value I, you can ignore the return value. However, if you use the return value, the following rules will be different depending on whether you use the prefix or suffix version of the operator, it:

If the operator is written before the variable, it increases the variable before returning its value.
If the operator is written after the variable, it adds the variable after returning its value.

For example:

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 is incremented before returning its value, which is why the new value of a and B is equal to 1.

However, let C = a++ is incremented after returning its value, which means that C obtains the original value of a of 1, then a self increases and a equals 2.

Unless you need to use i++ for specific work situations, it is recommended that you use ++i and – I in all cases because they modify I and return the value of the behavior in accordance with our expectations.

Unary subtraction operator

A value is added before the symbol--called a unary subtraction operator:

Copy Code code as follows:

Let three = 3
Let Minusthree =-three//Minusthree equals-3
Let Plusthree =-minusthree//Plusthree equals 3, or "Minus minus three"

The unary subtraction operator (-) is directly added to the front, before the value it functions, without any blank space.

Unary plus operator

The unary plus operator (+) returns the value of its function without any change:

Copy Code code as follows:

Let Minussix =-6
Let Alsominussix = +minussix//Alsominussix equals-6

Although the unary plus operator does not actually perform anything, you can use it to provide a symmetric positive number when you also use the operator of a unary offload.

Compound assignment operator

Swift provides a compound assignment operator similar to the C language, which combines assignment with another operation. For example, like an additive assignment operator (+ =):

Copy Code code as follows:

var a = 1
A + + 2
A is now equal to 3

The expression A + + 2 is more refined than a = a + 2. The addition assignment operator can effectively combine addition and assignment into one operation, while performing both tasks.

Note that the compound assignment operator does not return a value. For example, you cannot write let b = + = 2, which differs from the increment and decrement operator mentioned above.

A complete list of composite assignment operators can be found in the [Expressions] section

Comparison operators

Swift supports comparison operators for all standard C

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)

Note: Swift provides two identical operators (= = = and!==) to test whether two object references come from the same object instance. See classes and structures for details. Each comparison operator returns a BOOL value to indicate whether the statement is true:

Copy Code code as follows:

1 = 1/True, because 1 is equal to 1
2!= 1//True, because 2 is isn't 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

Comparison operators are typically used in conditional statements, such as if statements:

Copy Code code as follows:

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 are indeed equal to "the world"

To learn more about the IF statement, see Control flow.

Ternary conditional operator
the ternary conditional operator is a special operator that has three parts, in the form of question? Answer1:answer2. This is a shortcut to test two expressions based on whether the input is true or false. What if question? When True, it evaluates answer1 and returns its value; Otherwise, it evaluates the Answer2 and returns its value. The ternary conditional operator is the simplification of the following code:

Copy Code code as follows:

If question {
} else {

Here for an example, calculate the height of a table row pixel, if the row has a head, the row height should be 50 pixels, higher than the content of the height. If the row has no header is 20 pixels:
Copy Code code as follows:

Let Contentheight = 40
Let Hasheader = True
Let RowHeight = Contentheight + (hasheader? 50:20)
RowHeight is equal to 90

The preceding example can also be used in the following code:
Copy Code code as follows:

Let Contentheight = 40
Let Hasheader = True
var rowHeight = Contentheight
If Hasheader {
RowHeight = RowHeight + 50
} else {
RowHeight = RowHeight + 20
RowHeight is equal to 90

The first example uses the ternary conditional operator, which means that rowheight can be set to the correct value in one line of code. This is simpler than the second example, and does not require an extracurricular rowheight variable because its value does not need to be modified in an if statement.

The ternary conditional operator provides an efficient way to determine which expression will be executed. But be careful. Use the ternary conditional operator, whose simplicity, if overused, can lead to difficulty reading the code. To avoid combining ternary conditional operators of multiple instances into a single compound statement.

Range operator

Swift contains two range operators that express a range of values quickly

Enclosing range operator

The enclosing range operator (A...B) defines a range, from a to B, and includes the values of A and B.

The range operator is useful when you want to iterate over all possible values within a range, such as the for-in loop

Copy Code code as follows:

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

To learn more about for-in loops, see control flow.

Semi-enclosed area operator

Semi-enclosed area operator (a.. b) defines the range from a to B, but does not include B. It is considered semi-closed because it contains the first value and does not contain the final value.

Semi-enclosed ranges are used explicitly when you use a zero-based list, such as an array, it is useful to count to (but not include) the length of the list:

Copy Code code as follows:

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 contains four items, but 0. . Count to 3 (the index of the last item in the array), because it is a semi-closed range. For more information about arrays, see arrays

logical operators

Logical operators modify or combine Boolean logical values True and false. Swift supports these three standard logical operators based on the C language:

Logical Not (!a)
Logical and (a && b)
Logical OR (A | | b)

Logical non-operator

The logical non-operator (!a) converts a Bollean value, and true turns false,false to true.

The logical operator is a prefix operator and appears immediately before the value it modifies, without any whitespace, it is interpreted as "no", see the following example:

Let Allowedentry = False
If!allowedentry {
println ("ACCESS DENIED")
This sentence if!allowedentry can be understood as "if not allowedentry." Executes only subsequent rows if "not Allowedentry" is true; That is to say if Allowedentry is false.

In this example, carefully selected Boolean constants and variable names can help keep the code readable and concise while avoiding double negative or confusing logical statements.

Logic and operators

Logic and operators: (a && B) the expression is correct when a and B two values must be true at the same time.

Where A or B has any value of false, the logical AND operator representations are not valid, and must be true when both of the values are valid. In fact, if the first value is false, the second value will not even be judged, because it must be true for two values, and if there is one false, then there is no need to judge it further down. This is called a short-circuit condition.

The following example judges the values of two bool types and outputs only those values that are true: Welcome. Failure outputs "ACCESS DENIED":

Copy Code code as follows:

Let Entereddoorcode = True
Let Passedretinascan = False
If Entereddoorcode && Passedretinascan {
println ("welcome!")
} else {
println ("ACCESS DENIED")

Logical OR operator

Expression (A | | b The expression is valid if either A or B has one true.

Similar to the above logic and operators, the logic or operator uses short-circuit conditions to determine that if the left side is true, then the right side is not judged because the overall result does not change.

In the following example, the first Boolean value (Hasdoorkey) is false, but the second value (Knowsoverridepassword) is true. Because both have a value of true and the entire expression evaluates to true, the correct output is: welcome!

Copy Code code as follows:

Let Hasdoorkey = False
Let Knowsoverridepassword = True
If Hasdoorkey | | Knowsoverridepassword {
println ("welcome!")
} else {
println ("ACCESS DENIED")
Prints "welcome!"

Compound logical expression

You can combine multiple logical operators to create a longer compound expression:

Copy Code code as follows:

If Entereddoorcode && Passedretinascan | | Hasdoorkey | | Knowsoverridepassword {
println ("welcome!")
} else {
println ("ACCESS DENIED")
Prints "welcome!"

Compared to the previous two separate operators, this time through multiple nesting, we above the &&, | | Operators combine to form a long compound expression. Looks a bit forgive, in fact, the essence or two-phase comparison, can be simply seen as a && B | | C | | D, from left to right based on operator Precedence to judge, pay attention to distinguish &&, | |, as long as you keep in mind that the operational logic && need both true, | | Only need one side is true the operator can parse the whole compound expression and see the essence through the phenomenon.

Explicit brackets (translated into Chinese statements incoherent Tete mody forgive, anger of their own understanding. )

In a compound expression, we can add () to make the logical intent more explicit, in the example above, we can add parentheses to the first part to clarify the meaning.

Copy Code code as follows:

if (entereddoorcode && passedretinascan) | | Hasdoorkey | | Knowsoverridepassword {
println ("welcome!")
} else {
println ("ACCESS DENIED")
Prints "welcome!"

In a composite logical expression, an we can use parentheses to clearly indicate that we need to put a few values in a separate logical operation to judge the result, the final result based on () and then the next value to judge, look at the above example, just like our primary school subtraction, Without parentheses () we must be judged by the precedence of the operators, but with parentheses at this point, we need to first compute the logical operators in order to get their values. Use parentheses () in a logical expression to be more specific to your intentions.

Related Article

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: 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.