Less than or equal (a <= b
)
Note:
Swift also provides constant===
And nonconstant!==
These two comparison operators are used to determine whether two objects reference the same object instance. More details are in the class and structure.
Each comparison operation returns a Boolean value indicating whether the expression is true:
1 = 1 // true, because 1 equals 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 operations are mostly used in conditional statements, as shown in figureif
Condition:
Let name = "world" if name = "world" {println ("hello, world")} else {println ("I'm sorry \ (name ), but I don't recognize you ")} // output" hello, world ", because 'name' is equal to" world"
Aboutif
Statement, see control flow.
Ternary Conditional Operator)The special feature of the ternary conditional operation is that it has three operands, and its prototype isQuestion? Answer 1: Answer 2
. It briefly expressesProblem
Select either of them. IfProblem
Yes, returnAnswer 1
Results; if not true, returnAnswer 2
.
The following code is simplified by using the ternary conditional operation:
if question: { answer1}else { answer2}
Here is an example of computing table rows. If there is a header, the row height should be 50 pixels higher than the content height; if there is no header, only 20 pixels higher.
Let contentHeight = 40let hasHeader = truelet rowHeight = contentHeight + (hasHeader? 50: 20) // rowHeight is now 90
In this way, the write is simpler than the following code:
Let contentHeight = 40let hasHeader = truevar rowHeight = contentHeightif hasHeader {rowHeight = rowHeight + 50} else {rowHeight = rowHeight + 20} // rowHeight is now 90
The first code example uses a three-element conditional operation, so a line of code can give us a correct answer. This is much simpler than the second code.rowHeight
It is defined as a variable because its value does not need to be inif
Statement.
Conditional operations provide an efficient and convenient way to express two-choice. You need to pay attention to the fact that over-using ternary conditional operations will change from concise code to obscure code. We should avoid using multiple ternary conditional operators in a combined statement.
Interval OperatorsSwift provides two operators to easily express the value of a range.
Closed Interval OperatorClosed Interval operator (a...b
) Definea
Tob
(Includinga
Andb
. ? The closed-interval operator is very useful when iterating all values in a range, for example, infor-in
In the 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
Aboutfor-in
, See control flow.
Semi-closed intervalSemi-closed interval (a..b
) Define a slavea
Tob
But not includingb
. This is called a semi-closed interval because it contains the first value instead of the last value.
The practicality of the semi-closed interval is that when you use a list starting from 0 (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 ("the \ (I + 1) Name \ (names [I])")} // 1st people are Anna // 2nd people are Alex // 3rd people are Brian // 4th People Are Jack
The array has four elements,0..count
Count to 3 (subscript of the last element) because it is a semi-closed interval. For more information about arrays, see arrays.
Logical operationThe operation object of logical operations is a logical Boolean value. Swift supports three standard logical operations based on the C language.
- Non-logical (
!a
)
- Logic and (
a && b
)
- Logic or (
a || b
) Non-logicalLogical non-operation (!a
) Returns the inverse of a Boolean value so thattrue
Changefalse
,false
Changetrue
.
It is a prefix operator that must appear before the operand without spaces. ReadingNon-
Then, let's look at the following example:
Let allowedEntry = falseif! AllowedEntry {println ("access denied")} // output "access denied"
if!allowedEntry
The statement can be read as "if it is not a alowed entry. ", The next line of code is only available if" non-allow entry "istrue
, That isallowEntry
Isfalse
Is executed.
In the sample code, careful selection of Boolean constants or variables helps code readability and avoids the use of double logical non-computation or chaotic logical statements.
Logic andLogic and (a && b
) Onlya
Andb
All aretrue
The value of the entire expression istrue
.
If any value isfalse
The value of the entire expression isfalse
. In fact, if the first value isfalse
So it does not calculate the second value, because it cannot affect the results of the entire expression. This is called "short-circuit evaluation )".
In the following example, there are only twoBool
Alltrue
Value:
Let enteredDoorCode = truelet passedRetinaScan = falseif enteredDoorCode & passedRetinaScan {println ("Welcome! ")} Else {println (" access denied ")} // output" access denied"
Logic orLogic or (a || b
) Is a continuous|
The central operator. It indicates that one of the two logical expressions istrue
, The entire expression istrue
.
Similar to logic and operation, the logic is also short-circuit calculation. When the expression on the left end istrue
Will not calculate the expression on the right, because it cannot change the value of the entire expression.
In the following sample code, the first Boolean value (hasDoorKey
) Isfalse
But the second value (knowsOverridePassword
) Istrue
So the entire expression istrue
To allow access:
Let hasDoorKey = falselet knowsOverridePassword = trueif hasDoorKey | knowsOverridePassword {println ("Welcome! ")} Else {println (" access denied ")} // output" Welcome! "
Combination LogicWe can combine multiple logical operations to express a compound logic:
If enteredDoorCode & passedRetinaScan | hasDoorKey | knowsOverridePassword {println ("Welcome! ")} Else {println (" access denied ")} // output" Welcome! "
This example uses multiple&&
And||
. However,&&
And||
You can always operate on only two values. Therefore, this is actually the result of three simple logical continuous operations. Let's explain:
If we enter the correct password and pass the retina scan, or we have a valid key, or we know the password reset in an emergency, we can open the door.
The first two cases are not met, so the result of the first two simple Logics is:false
But we know the password reset in an emergency, so the value of the entire complex expression is stilltrue
.
Use parentheses to specify priorityTo make a complex expression easier to understand, it is very effective to use parentheses to specify the priority, although it is not necessary. In the previous example about the door permission, we added a bracket to the first part to use it to make the logic clearer:
If (enteredDoorCode & passedRetinaScan) | hasDoorKey | knowsOverridePassword {println ("Welcome! ")} Else {println (" access denied ")} // output" Welcome! "
These parentheses make the first two values an independent part of the entire logical expression. Although the output results with and without parentheses are the same, the Code with parentheses is clearer for those who read the code. Readability is more important than simplicity. Please add parentheses where your code becomes clearer!