Ios swift learning diary 3-Basic Operators

Source: Internet
Author: User

Ios swift learning diary 3-Basic Operators

Operators are special symbols or phrases for checking, changing, and merging values. For example, the plus sign+Add two numbers (for examplelet i = 1 + 2). Complex operations such as logic and operators&&(For exampleif enteredDoorCode && passedRetinaScan), Or a convenient operator that adds 1 to the I value.++i.

Swift 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, to prevent equality operators (==. Numeric operators (+,-,*,/,%) Will detect does not allow value overflow, in order to avoid saving the variable because the variable is greater than or less than the range of its type can bear the exception results. Of course, you can use the Swift overflow operator to implement overflow. For more information, see overflow operators.

Different from the C language, in Swift, you can perform the remainder operation on floating point numbers (%), Swift also provides an interval operator that does not exist in the C language to express the values between two numbers ,(a..bAnda...b.

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

An operator has one, two, and three operators.

  • Unary operators operate on a single operation object (such-a). The unary operator is divided into the prefix and the Postfix operator. The prefix operator must be placed before the operation object (for example!b), The post operator must be followed by the operation object (suchi++).
  • Binary operators operate on two operation objects (for example2 + 3), Is set in the middle, because they appear between two operation objects.
  • Three-element operators operate on three operation objects. Like the C language, Swift only has one three-element operator, which is a three-element conditional operator (a ? b : c).

    The value affected by the operator is called the operand.1 + 2Medium, plus sign+Is a binary operator. Its two operands are values.1And2.

    Value assignment operator

    Value assignment (a = b), Indicating to usebTo initialize or updateaValue:

    Let B = 10var a = 5a = B // a is now 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 does not return any value for the value assignment operation. The following code is incorrect:

    If x = y {// This sentence is incorrect, because x = y does not return any value}

    This feature makes it impossible for you (==) In the wrong format (=), Becauseif x = yIs the error code. Swift helps you avoid these code errors from the bottom layer.

    Numeric operation

    Swift allows all numeric types to support the basic four arithmetic operations:

    • Addition (+)
    • Subtraction (-)
    • Multiplication (*)
    • Division (/)
      1 + 2 // equal to 35-3 // equal to 22*3 // equal to 610.0/2.5 // equal to 4.0

      Unlike C and Objective-C, Swift does not allow overflow in numeric operations by default. However, you can use the Swift overflow operator to overflow your purpose (for examplea &+ b). For more information, see overflow operators.

      Addition operators are also usedStringSplicing:

      "Hello," + "world" // equals to "hello, world"

      TwoCharacterValue orStringAnd oneCharacterValue to generate a newStringValue:

      Let dog: Character = "d" let cow: Character = "c" let dogCow = dog + cow // note: the original quotation marks are cute puppies and calves, however, in Windows OS, emoticon characters are not supported. Therefore, the common character // dogCow is now "dc"

      For more information, see concatenate character strings.

      Remainder operation

      Remainder operation (a % b) Is computingbThe number of times is just enough to accommodateaReturns the remainder of the result ).

      Note:

      Remainder operation (%In other languages. Strictly speaking, however, the result of the negative number operation of this operator is more suitable for "remainder" than "modulo.

      Let's talk about how to get the remainder, computing9 % 4First, you can calculate4The number of times that can be added.9Medium:

      2 times, very good. The remainder is 1 (marked in orange)

      In Swift:

      9% 4 // equal to 1

      To geta % bResults,%The following equations are calculated and output:RemainderAs a result:

      A = (B x multiple) + Remainder

      WhenMultipleWhen the maximum value is obtained, it will be able to accommodatea.

      Set9And4In the equation, we get1:

      9 = (4 × 2) + 1

      In the same way, let's calculate-9 % 4:

      -9% 4 // equal to-1

      Set-9And4Equation,-2Is the largest integer obtained:

      -9 = (4 × -2) + -1

      Remainder is-1.

      In the negativebFor remainder,bIs ignored. This meansa % bAnda % -bThe results are the same.

      Floating Point Number remainder Calculation

      Unlike C and Objective-C, Swift can perform remainder on floating point numbers.

      8% 2.5 // equal to 0.5

      In this example,8Except2.5Equal3Yu0.5So the result isDoubleValue0.5.

      Auto-increment and auto-increment operations

      Like the C language, Swift also provides the convenience of adding 1 or minus 1 to the variable itself (++) And auto-subtraction (--. The operation objects can be integer and floating point. ?

      Var I = 0 ++ I // now I = 1

      Each call++i,iWill add 1. Actually,++iYesi = i + 1And--iYesi = i - 1.

      ++And--It is both a front-end and a back-end operation.++i,i++,--iAndi--All are valid statements.

      Note that these operators have been modified.iThere is a return value. If you only want to modifyiThen you can ignore the returned value. However, if you want to use the return value, you need to note that the values returned by the Pre-and Post-operations are different.

      • When++In the frontend mode, the system returns the result from the cursor.

      • When++Then, return the result before auto-increment.

        For example:

        Var a = 0let B = ++ a // both a and B are now 1let c = a ++ // a now 2, but c is the value 1 before a auto-increment.

        The above example,let b = ++aFirstaAdd 1 and then returna. SoaAndbAll are new values1.

        Whilelet c = a++Is returned firstaAnd thenaAdd 1. SocTheaThe old value of 1, andaAdd 1 and then change to 2.

        Unless you need to usei++Or we recommend that you use++iAnd--iBecause it is more logical to modify and then return such behavior.

        One dollar negative number

        You can use the prefix for the positive and negative numbers of values.-(That is, one dollar negative number) to switch:

        Let three = 3let minusThree =-three // minusThree equals-3let plusThree =-minusThree // plusThree equals 3, or "negative 3"

        One dollar negative number (-) Before the operand, there is no space in the middle.

        Mona1 normal number

        Mona1 normal number (+Returns the value of the operand without any change.

        Let minusSix =-6let alsoMinusSix = + minusSix // alsoMinusSix equals to-6

        Although one dollar+It is useless, but when you use a negative number to express a negative number, you can use a positive number to express a positive number, so that your code will be symmetric.

        Compound Assignment Operators)

        Like the powerful C language, Swift also provides other operators and value assignment operations (=) Composite assignment operator, plus assignment (+=) Is an example:

        Var a = 1a + = 2 // a is now 3

        Expressiona += 2Yesa = a + 2A addition operation completes the addition and assignment.

        Note:

        The compound assignment operation does not return values,let b = a += 2This type of code is incorrect. This is different from the auto-increment and auto-subtraction operators mentioned above.

        The expression section contains a complete list of compound operators. ?

        Comparison

        Comparison operations in all standard C languages can be used in Swift.

        • Equal (a == b)
        • Not equal (a!= b)
        • Greater (a > b)
        • Less (a < b)
        • Greater than or equal (a >= b)
        • 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 figureifCondition:

          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"

          AboutifStatement, 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 expressesProblemSelect either of them. IfProblemYes, returnAnswer 1Results; 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.rowHeightIt is defined as a variable because its value does not need to be inifStatement.

          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 Operators

          Swift provides two operators to easily express the value of a range.

          Closed Interval Operator

          Closed Interval operator (a...b) DefineaTob(IncludingaAndb. ? The closed-interval operator is very useful when iterating all values in a range, for example, infor-inIn 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 interval

          Semi-closed interval (a..b) Define a slaveaTobBut 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..countCount to 3 (subscript of the last element) because it is a semi-closed interval. For more information about arrays, see arrays.

          Logical operation

          The 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-logical

            Logical non-operation (!a) Returns the inverse of a Boolean value so thattrueChangefalse,falseChangetrue.

            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!allowedEntryThe 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 isallowEntryIsfalseIs 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 and

            Logic and (a && b) OnlyaAndbAll aretrueThe value of the entire expression istrue.

            If any value isfalseThe value of the entire expression isfalse. In fact, if the first value isfalseSo 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 twoBoolAlltrueValue:

            Let enteredDoorCode = truelet passedRetinaScan = falseif enteredDoorCode & passedRetinaScan {println ("Welcome! ")} Else {println (" access denied ")} // output" access denied"
            Logic or

            Logic 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 istrueWill 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) IsfalseBut the second value (knowsOverridePassword) IstrueSo the entire expression istrueTo allow access:

            Let hasDoorKey = falselet knowsOverridePassword = trueif hasDoorKey | knowsOverridePassword {println ("Welcome! ")} Else {println (" access denied ")} // output" Welcome! "
            Combination 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 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:falseBut we know the password reset in an emergency, so the value of the entire complex expression is stilltrue.

            Use parentheses to specify priority

            To 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!

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.