An operator is a special symbol or phrase that checks, changes, and merges values. For example, a plus sign adds + two numbers, such as let i = 1 + 2 . Complex operations such as logic and operators && (such as if enteredDoorCode && passedRetinaScan ), or the convenience operator increment operator with the I value plus 1, ++i and so on.
Swift supports most of the standard C-language operators and improves many features to reduce general coding errors. For example, the assignment ( = ) does not return a value to prevent == errors caused by assigning an assignment to the place where you want to judge the equality operator (). The numeric operator (,,,, and + - * / % so on) detects that a 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 an interval operator (and) that C does not have a value between two numbers, a..b 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, which precede the operands ( !b for example) with the predecessor operator, and the post operator follows the action object (for example i++ ).
- The binary operator operates on two operands (such as
2 + 3 ), which are central because they appear between two operand objects.
- The ternary operator operates on three operands, and as in C, 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, and in the expression 1 + 2 , the plus sign + is a two-tuple operator, and its two operands are values 1 and 2 .
Assignment operators
Assignment operation ( a = b ), which represents the value b to initialize or update with the value a :
let b = 10var a = 5a = 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) = (1, 2)// 现在 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 for you to write () wrong () == = , because the if x = y error code, Swift from the bottom to help you avoid these code errors.
Numeric operations
Swift enables all numeric types to support the basic arithmetic:
- Addition (
+ )
- Subtraction (
- )
- Multiplication (
* )
- Division (
/ )
1 + 2 // 等于 35 - 3 // 等于 22 * 3 // 等于 610.0 / 2.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 (for example a &+ b ). See overflow operator for details.
The addition operator is also used for String stitching:
"hello, " + "world" // 等于 "hello, world"
Two Character values or one String and one Character value, the addition generates a new String value:
let dog: Character = "d"let cow: Character = "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 that the calculation is b just good enough to be able a to fill, returning the part that is more than that.
Attention:
The redundancy 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 the remainder is calculated 9 % 4 , and 4 How many times you calculate it will just fit 9 in:
Twice times, very good, that remainder is 1 (marked in orange)
In Swift, this is the expression:
9 % 4 // 等于 1
To get a % b The result, the % following equation is computed and output 余数 as the result:
A = (bx multiples) + remainder
When 倍数 the maximum value is taken, it will just fit into the a box.
To put 9 and 4 substitute into the equation, we have to 1 :
9 = (4 × 2) + 1
The same method that I came to calculate -9 % 4 :
-9 % 4 // 等于 -1
To put -9 and 4 substitute the equation, -2 is the largest integer taken:
-9 = (4 × -2) + -1
The remainder is -1 .
When you balance negative numbers b , b the symbols are ignored. This means that a % b the a % -b results are the same as the result.
Calculation of floating-point number for remainder
Unlike the C language and objective-c,swift, floating-point numbers can be redundant.
8 % 2.5 // 等于 0.5
In this example, the 8 2.5 3 0.5 result is a Double value, except for equal to remainder 0.5 .
Self-increment and self-increment operations
Like the C language, Swift also provides an operator that facilitates the self-increment ( ++ ) and decrement () of the variable itself by 1 or minus 1 -- . Its operands can be shaped and floating-point.
var i = 0++i // 现在 i = 1
++i i The value is added 1 per call. In fact, ++i it's i = i + 1 shorthand, and --i it's i = i - 1 shorthand.
++and is -- both pre-and post-op. ++i, i++ , --i and i-- both are valid formulations.
We need to note that these operators are modified i with a return value. If you only want to modify i the value, 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 ++ it comes to the front, it comes back again.
When ++ the back is placed, the first return to the self-increment.
For example:
var a = 0let b = ++a // a 和 b 现在都是 1let c = a++ // a 现在 2, 但 c 是 a 自增前的值 1
For the above example, let b = ++a a add 1 and return a the value first. So a and b all are new values 1 .
Instead let c = a++ , it returns a the value first, and then a adds 1. So c get a The old value 1, and a add 1 to become 2.
Unless you need to use i++ the features, it is recommended that you use ++i and --i , because the first modification after the return of such behavior is more in line with our logic.
unary minus
The sign of a value can be - toggled with a prefix (that is, a unary minus):
let three = 3let minusThree = -three // minusThree 等于 -3let plusThree = -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 a dollar + does not work hard, but 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 the addition of an assignment ( += ):
var a = 1a += 2 // a 现在是 3
The expression a += 2 is a = a + 2 shorthand, and an assignment operation completes the addition and assignment of two things.
Attention:
Compound assignment operations do not return a 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:
Swift also provides === both the identity and !== the non-identical comparators 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 // true, 因为 1 等于 12 != 1 // true, 因为 2 不等于 12 > 1 // true, 因为 2 大于 11 < 2 // true, 因为 1 小于21 >= 1 // true, 因为 1 大于等于 12 <= 1 // false, 因为 2 并不小于等于 1
Comparison operations are used for conditional statements, such as if conditions:
let name = "world"if name == "world" { println("hello, world")} else { println("I‘m sorry \(name), but I don‘t recognize you")}// 输出 "hello, world", 因为 `name` 就是等于 "world"
For if statements, see Control flow.
Ternary conditional operation (ternary Conditional Operator)
The special of ternary conditional operation is that it is an operator with three operands, and its prototype is 问题?答案1:答案2 . It succinctly expresses 问题 the operation according to the establishment or not to make two choice one. Returns the result if 问题 it is set up 答案1 ; 答案2
The following code is simplified using the ternary conditional operation:
if question: { answer1}else { answer2}
Here is an example of calculating the row height of a table. If there is a table head, that row should be higher than the content height of 50 pixels; If there are no headers, just 20 pixels higher.
let contentHeight = 40let hasHeader = truelet rowHeight = contentHeight + (hasHeader ? 50 : 20)// rowHeight 现在是 90
This will be simpler than the following code:
let contentHeight = 40let hasHeader = truevar rowHeight = contentHeightif hasHeader { rowHeight = rowHeight + 50} else { rowHeight = rowHeight + 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, and does not need to be defined as a rowHeight 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
Swift 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 a b all values from to (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:
for index in 1...5 { println("\(index) * 5 = \(index * 5)")}// 1 * 5 = 5// 2 * 5 = 10// 3 * 5 = 15// 4 * 5 = 20// 5 * 5 = 25
About for-in , see control flow.
Semi-closed interval
The semi-closed interval ( a..b ) defines a a range from to b but not included 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.countfor i in 0..count { println("第 \(i + 1) 个人叫 \(names[i])")}// 第 1 个人叫 Anna// 第 2 个人叫 Alex// 第 3 个人叫 Brian// 第 4 个人叫 Jack
The array has 4 elements, but 0..count only 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 and (
a && b )
- Logic or (
a || b )
Logical Non-
The logical non-operation ( !a ) takes the inverse of a Boolean value, making true false it variable and false variable true .
It is a predecessor operator that needs to appear before the operand without spaces. Read 非 a It, and then we look at the following example:
let allowedEntry = falseif !allowedEntry { println("ACCESS DENIED")}// 输出 "ACCESS DENIED"
if!allowedEntryThe statement can be read as "If non-alowed entry." ", the next line of code is executed only if" non-Allow entry "is true allowEntry 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
The value of the a && b a b true entire expression is only when the logical and () expression is the value of only and true .
As long as any one value is, the value of the false entire expression is false . In fact, if the first value is false , then the second value is not computed 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 true allowed to enter:
let enteredDoorCode = truelet passedRetinaScan = falseif enteredDoorCode && passedRetinaScan { println("Welcome!")} else { println("ACCESS DENIED")}// 输出 "ACCESS DENIED"
Logical OR
Logic or ( a || b ) is a central operator that consists of two contiguous | components. It represents one of the two logical expressions true , and the entire expression is true .
Similar to logic and operation, logic or "short circuit calculation", when the left side of the expression is true , will not calculate the right expression, because it is not possible to change the value of the entire expression.
In the following sample code, the first Boolean value () is, hasDoorKey false but the second value () is, knowsOverridePassword so the true entire expression is true , allowing access:
let hasDoorKey = falselet knowsOverridePassword = trueif 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 && compound logic with multiple and || . But no matter what, && and || always only two values can be manipulated. 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 the retina scan; Or we have a valid key; Or if we know the password 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 Swift Learning Diary 3-Basic operator