Getting started with IOS development language Swift-Basic Operators

Source: Internet
Author: User

Getting started with IOS development language Swift-Basic Operators

Operators are special symbols or phrases used to check, change, and merge values. For example, the plus sign + adds two numbers (for example, let I = 1 + 2 ). Complex operations such as logic and operators & (such as if enteredDoorCode & passedRetinaScan), or convenient auto-increment operators + + I that increase the I value by 1.
Supports most operators in the Standard C language and improves many features to reduce regular encoding errors. For example, the value assignment operator (=) does not return values, so as to prevent errors caused by writing the place where the equal operator (=) is to be judged as a value assignment. Numeric operators (+,-, *,/, %, and so on) detect non-allowed value overflow, to avoid the exception caused by the variable being greater than or less than the range that its type can carry. Of course, you can use the Swift overflow operator to implement overflow. For more information, see overflow operators.
Unlike the C language, in Swift, you can perform the remainder operation (%) on floating point numbers. Swift also provides the interval operators that do not exist in the C language to express the values between two numbers, (.. B and... B). This facilitates us to express the values in a range.
This section only describes basic operators in Swift. Advanced operators include advanced operators, how to customize operators, and how to overload operators of custom types.

Terms

Operators include one, two, and three operators.
The unary operator operates on a single operation object (such as-). The unary operator is divided into the prefix and the Postfix operator. The prefix operator must be placed before the operation object (such! B). The post operator must follow the operation object (for example, I ++ ).
Binary operators operate on two operation objects (such as 2 + 3), which are left in the middle because they appear between the two operation objects.
Three-element operators operate on three operation objects. Like C, Swift only has one three-element operator, that is, the three-element conditional operator (? B: c ).
The value affected by the operator is called the operand. In expression 1 + 2, the plus sign + is a binary operator, and its two operands are values 1 and 2.

Value assignment operator

Value assignment (a = B) indicates that the value of B is used to initialize or update the value of:

let b = 10
var a = 5
a = b
// a is now equal to 10
If the right side of the assignment is a multivariate group, its elements can be immediately decomposed into multiple variables or variables:

let (x, y) = (1, 2)
// Now x equals 1, y equals 2
Unlike C and Objective-C, Swift's assignment operation does not return any value. So the following code is wrong:

if x = y {
    // This sentence is wrong because x = y does not return any value
}
This feature prevents you from writing (==) into (=) by mistake. Since if x = y is an error code, Swift helps you avoid these error codes from the bottom.


Numerical operations
All numeric types in support the basic four arithmetic operations:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)

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 does not allow overflow in numerical operations by default. But you can use Swift's overflow operator to achieve your intended overflow (such as a & + b). See the overflow operator for details.
Addition operator can also be used for String splicing:

"hello," + "world" // equals "hello, world"
Two Character values or a String and a Character value, the addition will generate a new String value:

let dog: Character = "d"
let cow: Character = "c"
let dogCow = dog + cow
// Translator's Note: The original quotes are very cute puppies and calves, but emoticons are not supported under win os, so they are changed to ordinary characters
// dogCow is now "dc"
For details, please refer to the combination of characters and character strings.


Remainder operation
The remainder operation (a% b) is to calculate how many times b just fits into a and returns the extra part (remainder).
Note:
The remainder operation (%) is also called modulus operation in other languages. However, strictly speaking, we look at the result of the operator's operation on negative numbers, "remainder" is more appropriate than "modulo".
Let ’s talk about what the balance is. Calculate 9% 4. You first need to calculate how many times 4 will fit into 9:

2 times, very good, the remainder is 1 (marked in orange)
Expressed this way in Swift:

9% 4 // equal to 1
To get the result of a% b,% calculated the following equation and output the remainder as the result:
× multiples) + remainder
When the multiple is the maximum, it will just fit into a.
Substituting 9 and 4 into the equation, we have 1:

9 = (4 × 2) + 1
The same method, let's calculate -9% 4:

-9% 4 // equal to -1
Substitute -9 and 4 into the equation, and -2 is the largest integer obtained:

-9 = (4 × -2) + -1
The remainder is -1.
When finding the remainder of negative number b, the sign of b is ignored. This means that the results of a% b and a% -b are the same.
Floating-point remainder calculation
Unlike C and Objective-C, floating point numbers can be surplus in Swift.

8% 2.5 // equals 0.5
In this example, 8 divided by 2.5 equals 3 and 0.5, so the result is a Double value of 0.5.

Increment and increment
Like C language, Swift also provides convenient increment (++) and decrement (–) operators for adding or subtracting 1 to the variable itself. Its operation objects can be integer and floating point.

var i = 0
++ i // now i = 1
Each time ++ i is called, the value of i will increase by 1. In fact, ++ i is shorthand for i = i + 1 and –i is shorthand for i = i-1.
++ and – are both front and back operations. ++ i, i ++, –i and i– are all valid wordings.
We need to note that these operators have a return value after modifying i. If you only want to modify the value of i, then you can ignore this return value. But if you want to use the return value, you need to pay attention to the difference between the return value of the pre and post operations.
When ++ comes in front, first increase and then return.
When ++ comes after, return first and then increase.
  E.g:

var a = 0
let b = ++ a // a and b are now 1
let c = a ++ // a is now 2, but c is the value of a before incrementing 1
In the above example, let b = ++ a adds 1 to a before returning the value of a. So both a and b are new values 1.
And let c = a ++, the value of a is returned first, and then a is incremented by 1. So c gets the old value of a, and a increases to 1 and becomes 2.
Unless you need to use the features of i ++, it is recommended that you use ++ i and –i, because the behavior of returning after first modification is more in line with our logic.


Unary minus sign

The sign of the value can be switched using the prefix-(that is, the unary minus sign):

let three = 3
let minusThree = -three // minusThree is equal to -3
let plusThree = -minusThree // plusThree is equal to 3, or "negative negative 3"
Unary minus sign (-) is written before the operand with no space in between.


Unary positive sign

Unary positive sign (+) returns the value of the operand without any change.

let minusSix = -6
let alsoMinusSix = + minusSix // alsoMinusSix equals -6
Although unary + does useless work, when you are using unary minus sign to express negative number, you can use unary positive sign to express positive number, so your code will have symmetric beauty.
Compound Assignment Operators
Like the powerful C language, Swift also provides compound assignment operators that combine other operators with assignment operations (=), plus assignment (+ =) is one example:

var a = 1
a + = 2 // a is now 3
The expression a + = 2 is a shorthand for a = a + 2. An addition operation completes addition and assignment.
Note:
Compound assignment operation has no return value, let b = a + = 2 This kind of code is wrong. This is different from the increment and decrement operators mentioned above.
Has a complete list of compound operators in the expression chapter.


Comparison operation
All standard C comparison operations can be used in Swift.
Is equal to (a == b)
Is not equal to (a! = B)
Is greater than (a> b)
Is less than (a <b)
Is greater than or equal to (a> = b)
Less than or equal to (a <= b)
Note:
Also provides identity === and inequity! == These two comparisons determine whether two objects refer to the same object instance. More details are in class and structure.
Each comparison operation returns a Boolean value that identifies whether the expression is true:

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
Comparison operations are mostly used in 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")
}
// Output "hello, world", because `name` is equal to" world "
For the if statement, please see the control flow.


Ternary conditional operation
The speciality of ternary conditional operation is that it is an operator with three operands, and its prototype is Question? Answer 1: Answer 2. It succinctly expresses the choice of two alternatives based on whether the question is true or not. If the question is true, return the result of answer 1; if not, return the result of answer 2.
Using ternary conditional operations simplifies the following code:

if question: {
  answer1
} else {
  answer2
}
Here is an example of calculating the row height of a table. 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 = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader? 50: 20)
// rowHeight is now 90
Written like this will be more concise than the following code:

let contentHeight = 40
let hasHeader = true
var rowHeight = contentHeight
if hasHeader {
    rowHeight = rowHeight + 50
} else {
    rowHeight = rowHeight + 20
}
// rowHeight is now 90
The first code example uses ternary conditional operations, so one line of code will allow us to get the correct answer. This is much simpler than the second piece of code, without the need to define rowHeight as a variable, because its value does not need to be changed in the if statement.
The ternary conditional operation provides an efficient and convenient way to express the choice between two. It should be noted that excessive use of ternary conditional operations will change from concise code to incomprehensible code. We should avoid using multiple ternary conditional operators in a combined statement.


Interval operator
Provides two operators that are convenient for expressing the value of an interval.
Closed interval operator
The closed interval operator (a ... b) defines an interval containing all values from a to b (including a and b). ? The closed interval operator is very useful when iterating over all values in an interval, 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
For for-in, please see control flow.
Semi-closed interval
The semi-closed interval (a..b) defines an interval from a to b but excluding b. It is called a semi-closed interval because the interval contains the first value but not the last value.
The utility of semi-closed intervals 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.count
for i in 0..count {
    println ("第 \ (i + 1) Personal name \ (names [i])")
}
// The first person is Anna
// The second person is called Alex
// The third person is Brian
// The fourth person is called Jack
The array has 4 elements, but 0..count only counts to 3 (the subscript of the last element) because it is a semi-closed interval. For the array, please refer to the array.


logic operation
The operation object of logical operation is logical Boolean value. Swift supports three standard logical operations based on C language.
Logical negation (! A)
Logical AND (a && b)
Logical OR (a || b)
Logical negation
Logical negation (! A) inverts a Boolean value, making true become false and false becomes true.
It is a pre-operator, which needs to appear before the operand without spaces. It is pronounced non-a, and then we look at the following example:

let allowedEntry = false
if! allowedEntry {
    println ("ACCESS DENIED")
}
// output "ACCESS DENIED"
If! AllowedEntry statement can be read as "if not alowed entry.", The next line of code is only if "not allow entry ”is true, which is executed when allowEntry is false.
In the sample code, carefully choose Boolean constants or variables to help the readability of the code, and avoid the use of double logical negation, or chaotic logic statements.
Logical AND
Logical AND (a && b) expresses that only when the values of a and b are true, the value of the entire expression will be true.
As long as any one value is false, the value of the entire expression is false. In fact, if the first value is false, then the second value is not calculated, because it is impossible to affect the result of the entire expression. This is called "short-circuit evaluation".
In the following example, only two Bool values are true when the entry is allowed:

let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
    println ("Welcome!")
} else {
    println ("ACCESS DENIED")
}
// output "ACCESS DENIED"
Logical OR
Logical OR (a || b) is a middle operator consisting of two consecutive | s. It indicates that one of the two logical expressions is true, and the entire expression is true.
Similar to logic and operation, logical OR is also "short circuit calculation". When the expression on the left end is true, the expression on the right will not be calculated because it is impossible to change the value of the entire expression.
In the following sample code, the first boolean value (hasDoorKey) is false, but the second value (knowsOverridePassword) is true, so the entire expression is true, so entry is allowed:

let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
    println ("Welcome!")
} else {
    println ("ACCESS DENIED")
}
// output "Welcome!"
Combinational logic
We 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 compound logic with multiple && and ||. But no matter what, && and || can only operate on two values. So this is actually the result of three simple logical consecutive operations. Let's interpret it:
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 to enter.
We are not satisfied with the first two cases, so the result of the first two simple logic is false, but we know the password reset in an emergency, so the value of the entire complex expression is still true.


Use parentheses to clarify priority
In order to make a complex expression easier to understand, it is effective to use parentheses to clarify the priority where appropriate, although it is not necessary. In the last example of the permission of the door, we put a bracket around the first part, and using it looks more logical:

if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
    println ("Welcome!")
} else {
    println ("ACCESS DENIED")
}
// output "Welcome!"
The parentheses make the first two values regarded as an independent part of the whole logical expression. Although the output results with and without brackets are the same, the code with brackets is clearer for those who read the code. Readability is more important than conciseness, please put parentheses where you can make your code clear!

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