Wednesday, July 2, 2014

Basic operator in Swift Langauge

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 = b
// a is now equal to 10

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

let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2

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

if x = y {
    // this is not valid, because x = y does not return a value
}
This feature prevents the assignment operator (=) from being used by accident when the equal to operator (==) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code.

Arithmetic Operators


Swift supports the four standard arithmetic operators for all number types:
Addition (+) Subtraction (-) Multiplication (*) Division (/)

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

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default. You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b). See Overflow Operators. The addition operator is also supported for String concatenation:
"hello, " + "world"  // equals "hello, world"

Two Character values, or one Character value and one String value, can be added together to make a new String value:

let firstname: Character = "John"
let lastname: Character = "Howdy"
let name = firstname+ lastname

// name is equal to "JohnHowdy"

No comments:

Post a Comment