Basic operators of Swift, Swift Operators

Source: Internet
Author: User

Basic operators of Swift, Swift Operators

Today, I learned the most basic knowledge about Swift language. Here are some of my understandings and conclusions. I hope to help more people understand the area. If anything is wrong, I hope you can point out that, so that timely correction can be made.


  Basic Operators

An operator is a special symbol or phrase that you can use to check, change, or combine values.

The operators are all mona1, binary, or ternary:

  • Unary operators operate on a single object mainly including: prefix operators (such as-,! A) and suffix operators appear after the object (such as I ++, I --).
  • Binary operators operate on two objects between them, mainly including-, +, *,/, %, <,>, =. (For example, a-B, a + B, a * B, a/B, a % B, a <B, a> B, a = B)
  • The three-element operator operates on two objects. Like the C language, Swift only supports one three-element OPERATOR: the three-element conditional operator (? B: c ).

  Value assignment operator

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


let b = 2
 var a = 3
 a = b
// At this time the value of a is equal to the value of b is 2
 

If the data assigned on the right is a tuple of multiple data, its elements can be multiple constants or variables assigned at one time

let (a, b) = (1, 2)
// a is equal to 1, b is equal to 2
Unlike C and Objective-C, the assignment operator in Swift does not return itself as a value. So the following code is illegal:

if x = y {
// Error, because x = y does not return a value
}
Math operator
Swift supports four annotation operators for all numeric types:

Addition (+)
Subtraction (-)
multiplication(*)
division(/)
  E.g:

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's arithmetic operators do not allow value overflow by default. The addition operator is also applicable to string concatenation, for example:

"hello," + "world" // equals "hello, world"
 

Two characters, or a character and a string, can be combined into a new string:

let dog: Character = "dog"
let cow: Character = "cow"
let dogCow = dog + cow
// dogCow is equal to "dogcow"
Remainder operator

The remainder operator% refers to the remaining number when the divisor is divided by the dividend, such as (the remainder of 3% 2 is 1)

let a = 5
let b = 3
let c = a% b
// The value of c is 2
In the same method, if the value of a is -5, then the value of c after the remainder operation is -2, if the value of b is -3, the value of c will be 2, which means that the sign of the remainder operation is not subject to the dividend b Is affected only by the divisor a

Floating-point remainder calculation

Unlike C and OC, Swift's remainder operation can also be applied to floating point numbers:

let a = 8
let b = 2.5
let c = a% b
// Then the value of c is 0.5
Increment and decrement operator

Like C, Swift provides two operators: increment (++) and decrement (-), whose increment and decrement is 1, and can be used for any variable of integer or floating point type. Such as

var a = 0
++ a // The value of a is 1
--a // At this time the value of a is 0
It should be noted here that when the operation needs to return a value, the position of the increment and decrement operators is different for the result of the operation:

var a = 0
let b = ++ a // a and b are both 1
let c = a ++ // At this time, the value of a is 2 and the value of c is 1
let d = --a // At this time, the value of d is 1 and the value of a is 1
let e = a-- // At this time, the value of e is 1 and the value of a is 0
 

Compound assignment operator

Swift provides the same compound copy operator as C language, which means to combine assignment with another operator. Such as (+ =), (-=):

var a = 1
a + = 2 // At this time, the value of a is 3
a-= 3 // The value of a at this time is 0
 

The prototype of the addition assignment operator is a = a + 2, and the reason why it is written as (+ =) is that it can effectively combine addition and assignment into one operation, and perform both tasks simultaneously.

It should be noted that the compound copy operator does not return a value. For example, it is wrong to write let a = + = 1.



Comparison operator

Swift supports all C comparison operators.

Greater than (a> b)
Less than (a <b)
Greater than or equal to (a> = b)
Less than or equal to (a <= b)
Equal to (a = b)
Is not equal to (a! = B)
let a = 5
let b = 6
let c = 5
a> b // return false
c <b // return true
a> = c // return true
a <= c // return true
a == c // return true
a! = b // return true
This comparison operator is usually used in conditional statements, such as if statement

let a = "chk"
if a == "chk" {
    println ("hello, chk")
}
else {
    println ("not chk")
}
// The output result is hello, chk
 

We will study the if statement in detail later

 

Range operator

Swift provides two forms of range operators

1. Closed range operator

The closed range operator (a ... b) defines a range from a to b, and includes the values of a and b. Generally used in for -in loop statement

for i in 0 ... 5 {
    println ("The first \ (i) times")
}

// 0th time
//1st
//2nd
//the 3rd time
//4th
 

 

 

About the for-in statement, we will study it in depth later.

2. Semi-closed area operator

The semi-closed area operator (a..b) defines the range from a to b, but does not include b. It is considered semi-closed because it contains the first value, but not the final value.

Use a semi-closed range explicitly, when you use a zero-based list, such as an array, it is useful to count (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
Please note that the array contains four items, but the count is only 0 to 3 (the index of the last item in the array), because it is a semi-closed range. Information about arrays will be studied in depth later.

Ternary operator

Swift, like C, also supports ternary operations. Ternary operations are also bar operations. The main form is a? B: c. The expression means to judge the value of a. If the value of a returns true, the expression returns the value of b , If the value of a returns false, return the value of c. Below we use code to compare the advantages of the ternary operator:

let a = true
let b = a? 2: 3
// The value of b is 2
 

The above expression can also be written like this

let a = true
if a {
    reture 2
}
else {
    reture 3
}
// The result is 2
It is obvious that using the ternary operator is more concise and convenient. However, it should be noted that in order to ensure the readability of the code, it is best not to use multiple instances of the ternary conditional operator to form a compound statement.

 

Logical AND operator

Swift supports these three standard logical operators based on C language, and is usually used in conditional statements:

not (! a)
and (a && b)
or (a || b)
Logical not operator (! A) means that if it is not true, it returns true, otherwise it returns false

let a = true
if! a {
    println ("The condition is established")
}
else {
    println ("The condition does not hold")
}
// The output result is that the condition is not established
// Because a itself is correct, and the logical negation operator says that a is not correct, it returns false if it is not true.
 

 

 

 

The logical AND operator (A && B) means A and B. Both values must be true to return true, otherwise A and B will return false if one of them is false

let A = true
let B = false
if A && B {
    println ("The condition is true returns true")
}
else {
    println ("The condition is not true, return false")
}
// The output result is false if the condition is not satisfied
 

Logical OR operator (A || B) means that one of A and B is true, it returns true, if A and B are false, the result returns false

let A = true
let B = false
if A || B {
    println ("The condition is true returns true")
}
else {
    println ("The condition is not true, return false")
}
// The print result is true if the condition is true
It is worth mentioning here that whether the logical AND operator or the logical OR operator uses the short-circuit condition judgment method, for example, the logical AND operator (&&) must be true when both values are true, then when the left When the value of is false, the condition does not hold, there is no need to judge the value on the right side of the operator. The logical OR operator (||) is also the same reason. The logical OR operator (||) is established as long as a value is true, then when the value on the left is judged to be true, the condition is established, there is no need to Determine the value on the right side of the operator.

Compound logical expression

Logical expression is to combine multiple logical operators to create a longer compound expression:

let a = true
let b = false
let c = true
if! a || c && b {
    println ("The condition is established")
}
else {
    println ("The condition does not hold")
}
// The output result is that the condition is not established
 

The interpretation of compound logical expressions like this is generally judged from left to right according to the priority of the logical operators, (!, &&, ||) The priority of the three operators is the same, just remember Both logical and operator (&&) must be true to be true. Logic or operator (||) is true when both are true, so that the entire compound expression can be parsed correctly, and the essence must be seen through the phenomenon .

 

Explicit parentheses

This is easier to understand. In compound logic expressions, we can add () to make the logical intent more clear. For example, in the above code we add ()

let a = true
let b = false
let c = true
if! a || (c && b) {
    println ("The condition is established")
}
else {
    println ("The condition does not hold")
}
// The output result is that the condition is not established
 

In a logical expression, we can put several values in a single logical operation to judge the result, and then judge the result of the judgment in () and the previous or later value, and finally get the final result 

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.