Painted levels: being fostered fostered fostered

Tags: “iOS” “Swift 5.1” “Operator” author: Mu Ling Lo Review: QiShare team


Terms for operators: Operators are unary, binary, and ternary.

  • Unary operators operate on a single object (such as -a). Unary prefix operators can appear directly in front of their targets (e.g.! B), unary suffix operators appear directly after their targets (e.g. C!). .
  • Binary operators run on two targets (such as 2 + 3) and are infixes because they occur between the two targets.
  • A ternary operator operates on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a? B: c)

Assignment operator: The assignment operator (a = b) initializes or updates the value of a with the value of B.

Let b = 10 var a = 5 a = bCopy the code

If the right side of an assignment is a tuple with multiple values, the elements of the tuple can be decomposed into multiple constants or variables at once.

let (x, y) = (1, 2)//! < x = 1 , y = 2Copy the code

Unlike assignment operators in C and Objective-C, assignment operators in Swift do not return values themselves. The following declaration is invalid

if x = y {//! The < '=' operator does not return a value in Swift, so this is invalid and an error is reported. }Copy the code

This feature prevents the accidental use of the assignment operator = when the equal operator == is actually used, and Swift helps us avoid such errors in our code by invalidating x = y.

Arithmetic operator

  • add+
  • Reduction of-
  • take*
  • In addition to/
2 * 3 * 3 // equals 6Copy the code

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operator does not allow value overflow by default. We can select value overflow behavior by using Swift’s overflow operator (for example &+ b). See overflow operators String concatenation also supports addition operators:

"hello, " + "world"  // equals "hello, world"
Copy the code

The remainder operator (a % b) calculates how many b’s a will contain and returns the remaining value (called remainder).

9 % 4    // equals 1
-9 % 4   // equals -1
Copy the code

Unary – and + operators: You can use – (called the unary subtraction operator) to append directly to a running value without any Spaces to switch the sign of the value. The + (called the unary addition operator) is appended directly before the running value without any space. The unary addition operator + returns nothing but the value it operates on. Unary subtraction operator

let three = 3
let minusThree = -three       // minusThree equals -3
let plusThree = -minusThree   // plusThree equals 3, or "minus minus three"
Copy the code

Unary addition operator

let minusSix = -6
let alsoMinusSix = +minusSix  // alsoMinusSix equals -6
Copy the code

Even though the unary addition operator doesn’t actually do anything, we can use it to provide positive symmetry to our code when using the unary subtraction operator as a negative number. Compound assignment operator: Like C, Swift provides a compound assignment operator that combines the assignment = with another operator. For example, the addition assignment operator + = :

var a = 1
a += 2// a is now equal to 3
Copy the code

The expression a += 2 is shorthand for a = a + 2. In effect, the addition and assignment operators are combined into one operator that performs two tasks simultaneously. Note that the compound assignment operator does not return a value. For example, you cannot write let b = a += 2. Comparison operators: Swift supports all standard C comparison operators.

  • Is equal to the= =A == b
  • Is not equal to! =A! = b)
  • Is greater than>(A > B)
  • Less than<(A < b)
  • Greater than or equal to> =(A >= B)
  • Less than or equal to! =(a <= b)
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 1Copy the code

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

let name = "world"
if name == "world" {
    print("hello, world")
} else {
    print("I'm sorry \(name), but I don't recognize you")
}
// Prints "hello, world", because name is indeed equal to "world".
Copy the code

Compare tuples: Two tuples can be compared if they have the same type and the same value. Tuples are compared from left to right, one value at a time, until the comparison finds two unequal values. Compare the two values, and the result of the comparison determines the overall result of the tuple comparison. If all elements are equal, the tuple itself is equal. That is, as long as two different values of two tuples are found by sequential comparison on the premise of comparison, the comparison will be made and return, as the comparison result of tuples, the following values will not be compared. For example:

(1, "Zebra ") < (2, "apple") // Returns true because 1 is less than 2" Zebra "and "apple" will not compare: It does not matter that "Zebra" is not less than "Apple" because comparisons are already determined by the first element of the tuple, and when the first element of the tuple is the same, their second element will be compared. However, when the first element of a tuple is the same, their second element is compared, Here is the case (3, "apple") < (3, "bird") // Returns true because 3 is equal to 3, "apple" is less than "bird" (4, "dog") == (4, "dog") // Returns true because 4 is equal to 4, "Dog" is equal to the "dog"Copy the code

Another: a tuple can be compared with a given operator only if the given operator can be applied to every value in the corresponding tuple. For example, as shown in the following code, you can compare tuples of two types (String, Int) because you can compare String and Int values using the < operator. Conversely, tuples of two types (String, Bool) cannot be compared with the < operator, because the < operator cannot be applied to Bool values.

If (" blue ", 1) < (" purple ", 1) {print (" was established as a result, returned to the true ")} the if (" blue ", false) < (" purple ", true) {/ /! Print ("Binary operator '<' cannot be applied to two '(String, Bool)' operands")Copy the code

The Swift standard library contains only comparison tuples with fewer than 7 elements. To compare a tuple with seven or more elements, we must implement the comparison operator ourselves.

Also: Swift provides two identity operators (=== and! ==), which tests whether two object references refer to the same object instance identity operator: Because classes are reference types, multiple constants and variables may refer to a single instance of the same class. (The same is true for structures and enumerations, because they are always copied when assigned to constants or variables or passed to functions.) Swift provides two identity operators to find out whether two constants or variables refer exactly to the same instance of a class.

  • The same (= = =)
  • Not the same (! = =)

Note: The same === does not mean equal ==. === means that two constants or variables of class type refer to exactly the same class instance. Equal means that two instances are considered equal in value.

  1. Obj1 and obj2 constants are both class types and refer to instance objects of different classes
Let obj1 = uiView.init () let obj2 = uiView.init () let (x,y) = (obj1,obj2) if x === y {print(" Obj1 and obj2 constants are class types, } else{print(" Obj1 and obj2 constants are class types, and they refer to instance objects of different classes ")//! < Print result}Copy the code
  1. Obj1 and obj2 constants are both class types, and both refer to instance objects of exactly the same class
let obj1 = UIView.init() let obj2 = obj1 let (x,y) = (obj1,obj2) if x ! == y {print(" Obj1 and obj2 constants are class types and refer to instance objects of different classes ")} else{print(" Obj1 and obj2 constants are class types and refer to instance objects of identical classes ")//! < Print result}Copy the code

The ** ternary conditional operator: The ** ternary conditional operator is a special operator that has three parts and is used in the form question? Answer1: < br / > answer2. If the question is true, return answer1; Otherwise return to answer2. The ternary conditional operator is shorthand for:

if question {
    answer1
} else {
    answer2
}
Copy the code

The nil-coalescing (nil-coalescing) operator?? Unpack an optional a use form: a?? B. Unpack optional A; The default b is returned if a is nil, otherwise A is returned. A is always an optional type in an expression. And B must match the type of A. The nil-coalescing operator is shorthand for the following code:

a! = nil ? a! : b //<! Using ternary conditional operators and forced unpacking (a!) To access the value contained if a is not nil, otherwise return bCopy the code

The above code uses the ternary conditional operator and forces unpacking a! To access the value contained in optional A, if not nil, ignore the value of B and return the value of A, otherwise return b.

let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
Copy the code

Return operators: Swift contains multiple range operators. 1. Close Range Operator: Close Range Operator… Use the form (a… B) Define the range from a to B, including the values a and b, and the value of A must not be greater than b. The closed range operator is useful when we want to traverse the full range of all values, such as using for-in loops:

for item in 1... 8 { print(item)//! < print 12345678}Copy the code

2. Half-open Range Operator: the half-open Range Operator.. < Use form: A..

/* Print result: index :0, corresponding string: I Index :1, corresponding string: AM Index :2, corresponding string: am Zhangfei */ let array = [" I "," AM ","zhangfei"] for index in 0.. < array.count { //! Print (" index :\(index)" \(array[index])")} let array = [" I ","am","zhangfei"] for STR in array[0..<array.count] {print(STR)}Copy the code

One-sided Ranges: the extension of the use of Close Range operators and half-open Range operators. The closed range operator has an alternative form that allows the range to continue as far as possible in one direction. For example, the range of all elements in an array from index position 2 to the end of the array. In this case we can omit the value on the operator side. Specific use:

Let array = [" I ","am","zhangfei"] for STR in array[...] {print(STR)} for STR in array[1...] {print(STR)} For STR in array[...(array.count-1)] {print(STR)}Copy the code

The semi-open range operator also has a one-sided form and is written only with its final value, which is not part of the range because it is less than <. The specific use

4 for STR in array[..<array.count] {print(STR)}Copy the code

One-sided Ranges can be used in other contexts, not just in subscripts. The first value of the single-sided range cannot be ignored in the case of traversal, because traversal requires a clear idea of where to start. We can use a single-sided range that ignores the final value, but the range can continue indefinitely, so we need to make sure that we add an explicit end condition to our loop, and we can also check if the single-sided range contains a specific value. Specific examples are as follows:

let range = ... 5 range.contains(7) // false range.contains(4) // true range.contains(-1) // trueCopy the code

The scope can continue indefinitely, so make sure to add an explicit end condition to our loop as follows:

let range = 0... for i in range {//! < code executes indefinitely print(I)}Copy the code

Logical operators: Logical operators change Boolean logical values to true and false. Swift supports three standard c-based logical operators.

  • Logic is not!Such as:! a
  • Logic and&&Such as:a && b
  • Logic or||Such as:a || b

Resources: Swift 5.1 official programming guide


Recommended articles:

Swift 5.1(1) – Basic iOS UI state saving and recovery (3) iOS UI state saving and recovery (2) iOS UI state saving and recovery (1) common method of accurate timing In iOS Sign In With Apple (1) Weird dance weekly