Operators are special symbols or phrases that are used to detect, change, or combine values. For example, the addition operator (+) adds two numbers together (such as let i = 1 + 2). More complex examples include logic and operators && (such as if Entereddoorcode && Passedretinascan) and the increment operator ++i, which is the shortcut to add the value of I to 1.
Swift supports most of the standard C operators and improves several features to eliminate common coding errors. The assignment operator (=) does not return a value in order to prevent the use of the equals operator (= =) accidentally as an assignment operator. The arithmetic operator (+,-, *,/,%, and so on) detects and disables the value overflow so that the result of the operation is greater than or less than the allowable range of the type. You can use the Swift overflow operator to do overflow operations, see the "Overflow operator" section for details.
Unlike C,swift, you can take a float (%) on a floating-point number. Swift also provides two range operators (a.).<B and A...b), which is not in C, is used to denote a range of values.
This chapter describes the commonly used operators in Swift. The Advanced Operators section covers Swift's advanced operators, which describe how to customize operators and how to implement standard operators for custom types.
Terms
The operators are divided into unary, two and ternary:
Unary operators operate on a single target (such as-a). Unary prefix operators appear immediately before their targets (such as!b), and unary suffix operators appear immediately after their targets (such as i++).
The binary operator operates on two targets (for example, 2 + 3), which is the infix operator because it appears in the middle of two targets.
The ternary operator operates on three targets. Like C, Swift has only one ternary operator, which is the ternary conditional operator (a? b:c).
The value that the operator affects is called the operand. In expression 1 + 2, the symbol + is a two-dollar operator whose operands are values 1 and 2.
Assignment operator
The assignment operator (a = b) Initializes or updates the value of a with the value of B:
let10var5a = b // a is now equal to 10
If the right side of the assignment operator is a tuple with multiple values, its elements can be disassembled immediately to multiple constants or variables:
let (x, y) = (12) // x is equal to 1, and y is equal to 2
Unlike assignment operators in C and Objective-c, the assignment operator in Swift does not return a value on its own. The following statement is not possible:
if x = y {// this is invalid, because x = y does not return a value}
This feature prevents the assignment operator (=) from being mistakenly used as the equals operator (= =). Swift helps you avoid if x = y these errors appear in the code.
Arithmetic operators
Swift supports four standard arithmetic operators for numeric types:
Plus (+)
Minus (-)
Multiply (*)
Except (/)
12 // equals 353 // equals 223 // equals 610.02.5 // equals 4.0
Unlike arithmetic operators in C and Objective-c, the Swift arithmetic operator does not allow values to overflow by default. You can use Swift's overflow operator (such as a &+ b) to select a value overflow operation. See the "Overflow operator" section for more information.
The plus operator also supports string joins:
"hello, ""world" "hello, world"
Take the remainder operator
The Take-rest operator (a% b) calculates a number of multiples of B and returns the remainder (the remainder).
Attention
Remainder operator (%) In other languages, it is also called the modulo operator. However, in swift the operation of negative numbers is strictly to take redundancy rather than modulo.
This is an example of how the remainder operator works. To calculate 9 4, first calculate the maximum number of 4 that 9 can include:
9 has a maximum of two 4, and the remainder is 1 (the orange part above).
In Swift, this can be written:
94 // equals 1
To get the answer to a% B, the% operator calculates the following equation and returns remainder as its output:
a = (b × some multiplier) + remainder
The some multiplier is the maximum multiple of B that can be accommodated by a.
Insert 9 and 4 into this equation to derive:
9 = (4x2) + 1
The same method is used to calculate the value of negative a:
-94 // equal to -1
Insert 9 and 4 into the equation to obtain:
-9 = (4x-2) +-1
The result is a value of-1.
The negative value of B is ignored. That means a% B and a%-B are all the same answers.
Floating-point take-up calculation
Unlike the take-out operator for C and Objective-c, Swift's take-up operator can also calculate floating-point numbers:
82.5 // equals 0.5
In this example, 8 divided by 2.5 equals 3 and the remainder is 0.5, so the take-up operator returns a Double value of 0.5.
Self-increment and decrement operators
Like C, Swift provides a self-increment operator (+ +) and a self-decrement operator (--) that adds 1 or minus 1 to a numeric variable. You can use these two operators for any integer or floating-point variable.
var0 ++ i // i is now equal to 1
The value of each call to ++i,i will be added 1. Essentially, ++i is the abbreviation for i = i + 1. Again,-I is the abbreviation for i = i-1.
The + + and--symbols can be used for both prefixes and suffixes. Both ++i and i++ can increase the value of I by 1. Similarly,-I and I-can reduce the value of I by 1.
Note that the two operators also return a value when I is modified. If you just want to increase or decrease the value of I, you can ignore the return value. However, if you do use the return value, the prefix and suffix are used differently, according to the following rules:
If the operator is written before the variable, add 1 or minus 1 before returning the value.
If the operator is written after the variable, then the return value is added 1 or minus 1.
For example:
var0let b = ++ a // a and b are now equal to 1let c = a ++ // a is now equal to 2 but c is set to the value before addition 1
In the example above, let B = ++a increases the value of a before returning the value. This is why both A and B are equal to the new value 1.
However, let C = a++ increases the value of a after the return value. This means that C gets the old value 1, and a changes to equals 2.
Unless you need special use of i++, it is recommended that you use ++i and –i, as this is more in line with the typical expected behavior of modifying I and returning results.
unary minus operator
Symbols for numeric values can be toggled with a prefix-the unary minus operator:
let = 3let = -three // minusThree equals -3let = -minusThree // plusThree equals 3, or "negative three"
The unary minus operator (-) is added directly to the value to be manipulated without any spaces.
Unary plus operator
The unary plus operator (+) simply returns the value of the operation without making any changes:
let minusSix = -6let alsoMinusSix = +minusSix // alsoMinusSix equals -6
Although unary plus operators do not actually do anything, you can make your code look more symmetrical when both negative and positive numbers are available.
Compound assignment operator
Like C, Swift also provides a compound assignment operator that combines the replicator (=) with other operations. An example is the Add assignment operator (+ =):
a1a2// a equals 3
expression A + = 2 is an abbreviation for a = a + 2. Adding and assigning values to an operator allows you to perform two operations at a time.
Attention
The composite operator does not return a value. I can't write this. Let B = a + = 2. This is different from the addition and subtraction operators mentioned above.
The "Expressions" section has all the compound assignment operators introduced.
Comparison operators
Swift supports all standard C comparison operators:
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 two identity operators (= = = and!==) to test whether two object references refer to the same object instance. For more information, refer to the "Classes and structures" chapter.
Each comparison operator returns a Boolean value that indicates whether the statement is true:
1==1//trueBecause1Equals12!=1//trueBecause2Not equal to12>1//trueBecause2Greater than11<2//trueBecause1Less than21>=1//trueBecause1Greater than or equal to12<=1//falseBecause2not less than or equal to1
Comparison operators are typically used in conditional statements, such as the IF statement:
let"world"if"world" { println("hello, world"else { println("I‘m sorry \(name), but I don‘t recognize you")}//"hello, world"is"world"
To learn more about the IF statement, see the chapter "Control Flow".
Ternary conditional operator
The ternary conditional operator is divided into three parts, in the form of such question? Answer1:answer2. Returns one of those two expressions, based on whether question is true or false. Returns Answer1 if question is true, otherwise returns ANSWER2.
The ternary condition operator is shorthand for the following code:
if{ answer1}else{ answer2}
This is an example of calculating the row height of a table. If the row has a table header, the row height should be 50 points higher than the height of the content, and if there are no headers, 20 points High:
let40lettruelet5020)// rowHeight equals 90
The preceding example is an abbreviation for the following code:
let40lettruevar rowHeight = contentHeightif hasHeader { 50else { 20}// rowHeight equals 90
In the first example, the use of the ternary conditional operator means that rowHeight can set the correct value in one line of code. This is much simpler than the second example, and it is not necessary to define rowHeight as a variable, because its value is not necessarily changed in the IF statement.
The ternary conditional operator provides an efficient abbreviation for deciding which of the two expressions to use. However, be careful when using the ternary conditional operator. Abuse of words, although concise, but will make your code difficult to read. Try to avoid conforming multiple ternary condition operations to a compound statement.
Nil merge operator
Nil merge operator (a?? b) If a has a value, turn on optional A, otherwise if a is nil returns the value of B. Expression A is an optional type. Expression b must match the type stored in a.
The nil merge operator is an abbreviation for the following example:
aa! : b
The previous example uses the ternary conditional operator and forces it on (a!) and accesses the value in a when a is not nil, otherwise returns B. The nil merge operator provides a more elegant way to encapsulate this condition detection and opening, and the form is more concise and more readable.
Attention
If the value of a is non-nil, B is not evaluated. This is called a short-circuit evaluation.
The following example uses the nil merge operator to choose between a default color name and an optional user-defined color name:
let defaultColorName = "red"
var userDefinedColorName: String? // default is nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default "red"
The userdefinedcolorname variable is defined as an optional String, and the default value is nil. Because Userdefinedcolorname is an optional type, you can use the nil merge operator to get its value. In the example above, the operator is used to detect the initial value of a String named Colornametouse. Since Userdefinedcolorname is nil, the expression userdefinedcolorname?? Defaultcolorname returns the value of Defaultcolorname "red".
If you set a non-nil value to userdefinedcolorname and perform the nil merge operator again, then the value in Userdefinedcolorname will be used instead of the default one:
"green"nil"green"
Range operator
Swift includes two range operators, which represent abbreviations for the values of a range.
Closed range operator
The Closed range operator (A...B) defines a range from a to B, including the values of A and B. The value of a must not be greater than B.
The closed range operator is suitable for iterating over all the values in a range, 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
For more on the for-in cycle, see chapter "Control Flow".
Half Open Range operator
The semi-Open range operator (a..<b) defines a range from a to B, but does not include B. Because only the first value is included, excluding the last value, it is called half-open. As with the close range operator, the value of a cannot be greater than B.
The semi-open range is particularly useful for lists starting from 0, such as arrays, and always count to (but not include) the length of the list:
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, but0..<countonly to 3 (that is, the last index of the array) because it is a half-open range. For more information about arrays, see the "Arrays" section.
logical operators
Logical operators are used to modify or merge Boolean logical values of True and false. Swift supports three standard logic operators based on the C language:
Logical No (! A) Logical AND (a && b) Logical OR (a
Logical no operator
The logical no operator (!a) takes a Boolean value back and true changes false,false to true.
The logical no operator is a prefix operator that appears immediately before the value of its operation, with no spaces. It can be read as "not a", as shown in the following example:
let allowedEntry = false if !allowedEntry {
println("ACCESS DENIED")
}
// print "ACCESS DENIED"
The phrase if!allowedentry can be read as "If not allowed to enter". If "Do not allow entry" is true, subsequent code will execute; that is, if Allowedentry is false.
As in this example, it is prudent to use Boolean constants and variable names to help keep the code readable and concise, while avoiding double negation or confusing logical statements.
Logic and operators
The logical AND operator (a && b) creates a logical expression, and only two values are true when the value of the entire expression is true.
If one of the values is false, the entire expression is also false. In fact, the first value is false, and the second value is no longer seen because it is not possible to make the entire expression equal to true. This is called a short-circuit value.
This example detects two bool values, and only two values are true to allow access:
let enteredDoorCode = true let passedRetinaScan = false if enteredDoorCode && passedRetinaScan {
println("Welcome!")
} else {
println("ACCESS DENIED")
}
// print "ACCESS DENIED"
Logical OR operation
Logic or operation (A | | b) is an infix operator that is located between two adjacent characters. The expression that is created with it as long as one of the values is true, the value of the entire expression is true.
As with the above logic and operator, the logic or operator also uses a short-circuit value. If the expression on the left and the logical is true, the right part is not to be seen, because it does not change the output of the entire expression anyway.
In the following example, the first bool value I (Hasdoorkey) is false, but the second value (Knowsoverridepassword) is true. Because one of the values is true, the value of the entire expression is true, allowing access to:
let hasDoorKey = false let knowsOverridePassword = true if hasDoorKey || knowsOverridePassword {
println("Welcome!")
} else {
println("ACCESS DENIED")
}
// print "Welcome!"
The combination of logical operators
You can combine multiple logical operators to create a longer compound expression:
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword { println("Welcome!")
} else { println("ACCESS DENIED")
} // print "Welcome!"
This example uses multiple && | | operator to create a longer compound expression. However, && and | | The operator still operates only with two values, so this is actually a string of three smaller expressions. This example can be read as:
If we enter the right door and pass a retinal scan, or if we have a valid door key, or if we know the emergency replacement password, then we can allow access.
Based on the values of Entereddoorcode, Passedretinascan, and Hasdoorkey, the first two small expressions are false. However, you know the emergency replacement password, so the entire compound expression is still true.
The parentheses displayed
Sometimes it is also useful to have parentheses, although it is not strictly necessary to be strict, but it can make complex expressions easier to read. In the access control example above, it is useful to add parentheses to the first part of a compound expression:
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
println ("Welcome!")
} else {
println ("ACCESS DENIED")
}
// print "Welcome!"
The parentheses make it clear that the first two values are a separate part of the entire logic. The output of the composite expression does not change, but the intent of the entire expression is easier to read. Readability is more popular than simplicity, and parentheses can make your code more clear.
Swift Language Guide (ii) basic operators