(二) Swift [Basic Operators]

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

  • Unary Operators
var age = -3
var flag = false
flag = !flag
  • Binary Operators
let sum = 1 + 2
let multi = 2 * 3
  • Ternary Operators
let a = false
let value = a ? 1 : 2 // value is 2
  • Assignment Operator [The assignment operator (=) doesn’t return a value]
var age = 3
let value = 10
if age = value { //error
    // This is not valid, because age =  value does not return a value.
}
  • Arithmetic Operators
    Swift supports the four standard arithmetic operators for all number types:
  1. Addition (+)
  2. Subtraction (-)
  3. Multiplication (*)
  4. Division (/)

The addition operator is also supported for String concatenation:

var message = "hello "
message += "andy."

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators don’t allow values to overflow by default. You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b).

  • Remainder Operator
let a = 7 % 3 // 1
let b = -7 % 3 // -1
let c = -3 % 7 // -3
  • Unary Minus & Unary Plus Operator
var value = 3
let res = -value // -3
var len = -5
value = +len // -5
  • Compound Assignment Operators
var value = 1
value += 2 // 3
value -= 1 // 2
value *= 2 // 4
  • Comparison Operators
Equal to (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)
  • Range Operators
    1.The closed range operator (a...b)
    2.The half-open range operator (a..

  • Logical Operators [The Boolean logic values just only 'true' and 'false']
    Logical NOT (!a)
    Logical AND (a && b)
    Logical OR (a || b)

你可能感兴趣的:((二) Swift [Basic Operators])