Official Swift Language Document translation (4)-basic Operators

Source: Internet
Author: User
Tags arithmetic arithmetic operators bool logical operators valid
Basic Operators


An operator is a special symbol or phrase that is used to examine, manipulate, and combine values. For example, add a plus sign (+) that adds two values (let i = 1 + 2). More complex such as logic and (&&), self-increment (++i: show I plus a 1 return).

Swift supports most of the standard C operators and adds some functionality to eliminate errors. In order to differentiate from the operator (= =), the assignment operator (=) does not return any values. Arithmetic operators (+,-, *,/,%, etc.) Detect and avoid overflow of values, and when working with numbers, avoid unexpected results that are larger or smaller than the range of values allowed by the storage type. You can use the swift overflow operator described in overflow operators to reveal the overflow value.

Unlike C, Swift can use the remainder (%) in the calculation of floating-point numbers. Swift provides 2 types of domain operators (a.). <b and A...B) represent a series of values, and there is no such operator in C.

This section describes the operators that are commonly used by Swift. The Advanced Operators article describes the high-level operators and describes how to define your own custom operators and how to inherit your own custom type's standard operators.


Terminology


Operators are unary, two, ternary: Unary operators operate on a single target (such as-a). Unary prefix operators cling to their target (for example,!b). The unary suffix operator immediately follows their target (for example, i++) and the two-ary operator operates the directory with 2. Because they appear in the middle of the target, so called infix ternary operator operation Target is 3. Like C, Swift has only one 3-dollar operator: Ternary conditional operator (A?B:C)

The value that the operator affects is called the operand, in the expression 1+2, the plus sign (+) is a two-dollar operator with 2 operands: 1 and 2.


Assignment Operations


The assignment operator (A=B) indicates that the value of a is initialized or changed with the value of B.


    Let B = Ten
    var a = 5
    a = B
    //A is now equal to 10


If the right side of the assignment operator is a tuple object with multiple values, its elements can be decomposed into multiple variables or constants.


    Let (x, y) = (1, 2)
    //x are equal to 1, and y are equal to 2


Unlike assignment element characters in C and OC, the assignment operator in Swift itself does not return a value. The following statement is not valid:


    If x = y {
    //This isn't valid, because x = y does not return a value
    }


This feature avoids the error that the assignment operator (=) is treated as a equals operator (= =). Because if x=y is not valid, Swift helps to reduce this error in the code.


Arithmetic Operators


Swift provides 4 arithmetic operators for all numeric operations: plus (+) minus (-) multiplication (*) in addition to (/).


    1 + 2//equals 3
    5-3//equals 2
    2 * 3//equals 6
    10.0/2.5//equals 4.0


Unlike C and OC, the arithmetic operators in Swift do not allow values to overflow by default. But you can choose to allow it to overflow (a&+b), see Overflow Operators for specific operations.

The plus sign (+) is useful for connecting strings:


    "Hello," + "world"//equals "Hello, World"


A two-character value, a character and a string value, can form a new string value by a plus sign.



Other details see concatenating Strings and characters.


take the remainder operator


The fetch operator (A%B) calculates how many b a can hold and returns the remainder.


Note
The take-up operator is called a modulo operator in other languages. Strictly speaking, the take-up operator in Swift is more meaningful than a modulo operator in a negative operation.

The following figure shows how the take-up operator works, and in order to calculate 9%4, you first calculate how many 4 are included in 9.



It is clear that 9 contains 2 4. Then the remaining 1. In Swift, you can write:


    9% 4//equals 1


To determine the answer to the a%b, the remainder operator (%) returns reminder as its result output.



The value of some multiplier is the maximum value of a that can contain the number of B.


Put 9 and 4 in the equation above



When the value of a is negative, the take-up operator also applies.


-9% 4//Equals-1

Put 9 and 4 into the equation



Get the remainder of-1.


The identifier B is a sign that ignores a, so the values for a%b and A%-b are the same.


floating-point take-up calculation


Unlike C and OC, the take-up calculation in Swift also applies to floating-point numbers.


    8% 2.5//equals 0.5


In this example, 8 consists of 3 2.5. The remaining 0.5. So the above expression returns the number 0.5 of a double type.



self-increment self-subtraction operation


Like C, Swift provides the self-increment (+ +) self-decrement (--) operator, which represents the addition of 1 and minus 1 operations on a number. Any integer and floating-point variables can be used.


    var i = 0
    ++i//I now equals 1



The value of each call to ++i,i is added 1. In fact, ++i is the meaning of i=i+1. A similar I-i=i-1 means. + + and--identifiers can be either prefixed or suffixed. ++i and i++ are all plus 1 operations. In the same vein, both-I and i--are reduced by 1.


Note that the operator modifies and returns the value of I. If you just want to subtract 1 or 1 from the value stored in I, you can ignore the return value. If you want to use the return value, be aware of the difference between the prefix and suffix of + + and--. If the operator is before the variable, then the variable is incremented by 1 or reduced by 1 before returning. If the operator is behind a variable, then the variable returns and then increases by 1 or 1.


As in the following example:


    var a = 0 let
    b = ++a
    //A and B be now both equal to 1 let
    c = a++
    //A was now equal to 2, but C had bee n set to the pre-increment value of 1


In the above example, let B=++a will first add 1 in return. Let c=a++ a will return plus 1. So C gets the value before a of 1. Then a becomes 2.


If you do not have special needs, it is recommended to use the + + or--identifiers in all cases. Because they have a typical expected performance in terms of the return value after modifying the variable.


Unary minus operator


A signed number can be converted by adding a minus sign (-) in front of it, which is called a unary subtraction operator.


    Let three = 3 let
    minusthree =-three//minusthree equals-3 let
    plusthree =-minusthree//Plusthree equals 3, O R "Minus minus three"


The unary minus operator (-) is placed directly before the variable, with no spaces between them.


Unary plus operator


A signed number can be converted by adding a plus sign (+) in front of it, called a unary plus operator.


    Let Minussix =-6 let
    alsominussix = +minussix//Alsominussix equals-6


Although the unary plus operator does not actually do anything, you can make the code symmetrical by using the unary plus operator when you are writing the code with a positive number.


Compound assignment operator


Like C, Swift also provides the combination of the assignment operator (=) with other operators, called the compound assignment operator. The compound assignment operator in the following example is the plus (+ =) operator.


    var a = 1
    a + = 2
    //A is now equal to 3


The expression a+=2 is actually a=a+2. The fact that the plus and equal signs are combined into an operator to add and assign values.


Note that the
compound operator does not have a return value, you cannot write a let C = a+=2. This is not the same as the above-mentioned self-increment and self-reduction effects.

If you want to know more about the compound operator, see Expressions. A paper.


comparison Operators

Swift supports all C's 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 (A<=B)


Note
Swift also provides comparison operators for the attributes in 2 (= = = and!==), which is used to compare whether child objects inheriting the same object are the same instance. To learn more, see <span class= "X-name" ><a target=_blank href= "https://developer.apple.com/library/prerelease/ios/ Documentation/swift/conceptual/swift_programming_language/classesandstructures.html#//apple_ref/doc/uid/ Tp40014097-ch13-xid_95 "data-id="//apple_ref/doc/uid/tp40014097-ch13-xid_95 ">classes and Structures</a> </span> article.


Each comparison operator returns a value of type bool to indicate whether an 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 t o 1
    2 <= 1//False, because 2 is not less than than or equal to 1


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


    Let name = "World"
    if name = = "World" {
    println ("Hello, World")
    } else {
    println ("I ' m sorry \ (name), but I Don ' t recognize you
    }
    //prints "Hello, World", because name was indeed equal to "world"


To see more information about the IF statement, refer to the Control flow article.


Ternary conditional Operators


The ternary conditional operator is a special operator that contains 3 parts. It is in the form of Question?answer1:answer2. It selects one of the next 2 expressions based on the bool value derived from the questions. If the value of question is true then the Answer1 is chosen to calculate, whereas the Answer2 is chosen to calculate.

Ternary field operators are similar in the following form:


    If question {
    Answer1
    } else {
    answer2
    }


For example, you now need to calculate the height of a row in a table. The requirement is that if there is a row header, the height of the row is 50 units higher than the content height. If there is no row header, then the height of the row is 20 units higher than the content.


    Let contentheight =
    Hasheader = True let
    rowHeight = Contentheight + (hasheader? 50:20)
    //RowHeight is equal to 90


The code above is shorthand for the following code:


    Let contentheight =
    Hasheader = True
    var rowHeight = contentheight
    if hasheader {
    rowHeight = rowhe ight + +
    else {
    RowHeight = rowHeight + +
    }
    //RowHeight is equal to 90


The above example of using the ternary conditional operator indicates that the RowHeight value initialization can be done with a single line of code. More concise than the second example. And RowHeight does not need to be a variable, because its value does not change in the IF statement.

The ternary operator is efficient for the operation of 2 expressions, but should be used with caution. Excessive use can make your code difficult to understand. Avoid combining the use of multiple ternary operators.


range operator


Swift provides 2 range operators that represent the range of values.


Enclosing range Operators


The enclosing operator (A...B) represents the range of A through B, and also includes a and B. When you want to include all the numbers in a series of numbers, for example with a for. In an expression, it is better to use the enclosing operator.


    For index in 1...5 {
    println ("\ (index) times 5 are \ (Index * 5)")
    }
    //1 times 5 is 5
    //2 times 5 is 10
  //3 times 5 is (
    4 times 5 is)
    //5 times 5 is 25


Want to know more about for. In the loop, refer to the Control flow article.


semi-enclosing range operator


Semi-enclosing operator (a). <B) represents the number in the range A through B, but does not include B. The reason to call it semi-closed is that it includes the first number but does not contain the last number.

Semi-enclosing is useful when you use a list of 0 as the starting value for the array. It is convenient to iterate over the array (not including the last one).


ET names = ["Anna", "Alex", "Brian", "Jack"] let
count = Names.count for
i in 0..<count {
println ("Person \ (i + 1) is called \ (Names[i]) "
}
//person 1 are called Anna
//person 2 are called Alex
//person 3 is CAL LED Brian
//person 4 is called Jack

The above array contains 4 elements, but because it is a semi-enclosed 0: <count only counts to 3 (the last number in the array). For more details, refer to the arrays article.

But the actual code finds a. <b this way is not correct, and a. B has a semi-closed effect.


<span style= "color: #FF0000;" >let A = 4 for
i in 0..a {
   println (i)
} let

B = 5 for
i in 0...b {
    println (i)
}</sp An>


and A.. B and a...b do not have spaces in between, otherwise there will be problems


logical Operators


Logical operations modify and combine logical values of true and false. As with logical elements in C, Swift also provides 3 logical operators.


Logical non (!A) logic with (A&&B) logic or (a| | b


Logical Non-


Logical non (!A) inverts the Boolean value to True if the value changes to False,false. Logic is not a prefix operator, close to the front of the Boolean value, there can be no space in the middle, read as not a. Look at the following example.


    Let Allowedentry = False
    if!allowedentry {
    println ("Access DENIED")
    }
    //prints "Access DENIED"



The expression if!allowedentry means if not allowed entry. If the value of Allowedentry is false, the code in parentheses can be executed. In the example above, carefully selecting the constants and variables of the Boolean values makes the code easy to read and concise, avoiding double negation and confusing statements.


Logic and


Logic and operators (&&) such as the expression on either side of the symbol must be true, and the result of the operation is true. If there is a value of false, the expression is false. If the first value is false, then the second value is not evaluated to return false directly. Because the value of the expression must be false, you do not need to continue the value of the second expression. This method is called short-circuit calculation.

The following example takes into account 2 Boolean values, and the 2 Boolean values are true before processing continues.


    Let Entereddoorcode = True let
    Passedretinascan = False
    if Entereddoorcode && passedretinascan {
    println ("welcome!")
    } else {
    println ("Access DENIED")
    }
    //prints "Access DENIED"


Logical OR


The logical OR operator is to place the operator in the middle of two adjacent bytes. You can use it to create a logical expression in which any one of the values is true, and the expression returns True. As with the logic above, the logic or short-circuiting is also used to process the expression. If the value of an expression coordinate is true, the expression on the right is no longer executed. Because the value of the expression is true regardless of the value on the right.

In the following example, the first bool value is false, but the second bool value is true, then the value of the expression is true.


    Let Hasdoorkey = False let
    Knowsoverridepassword = True
    if Hasdoorkey | | Knowsoverridepassword {
    println ( "welcome!")
    } else {
    println ("ACCESS DENIED")
    }
    //prints "welcome!"


combination of logical operators


You can form a composite expression by combining multiple logical operators.


    If Entereddoorcode && Passedretinascan | | Hasdoorkey | | Knowsoverridepassword {
    println ("welcome!")
    } else {
    println ("ACCESS DENIED")
    }
    //prints " welcome! "


The above example is logically associated with (&&) and logic or (| | ) combined to form a composite expression. However, logic and logic or only the expression on both sides of the symbol, so the above compound expression can be understood as a combination of 3 expressions.

The above expression can be interpreted as:


If I enter the gate, I can enter the room by scanning the retina or having a door key or knowing the password of the door. Based on the values of Entereddoorcode, Passedretinascan, and Hasdoorkey, the first or the result of the operation is false. But you know the password, and the result of the expression is true.


Explicit parentheses


Sometimes when you do not need parentheses very much, we recommend that you use parentheses in the specification of your code is very necessary. In the case code above, the parentheses in the first section are useful for reading the code.


    if (entereddoorcode && passedretinascan) | | Hasdoorkey | | Knowsoverridepassword {
    println ("welcome!")
    } else {
    println ("ACCESS DENIED")
    }
    //prints " welcome! "


Parentheses allow the first 2 expressions to stand out from the entire expression, and we only consider these 2 values. The output of the expression does not change because the parentheses are added, but the expression becomes easy to read. Legibility is better than brevity. Using parentheses will make your intentions clearer.











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.