# Swift Basic Operators

Created By: Debasis Das (Jan 2016)

In this post we will touch upon the Swift Basic Operators using examples

### Swift Operators

Swift Operators are unary, binary or ternary

• Unary Operators – Operates on a single target
• unary operators are further divided into unary prefix (!flag) and unary postfix operators (i++)
• Binary Operators – Operates on two targets and an infix that appears between the two targets e.g x+y
• Ternary Operator – Operates on 3 targets. Swift has only one ternary operator that is the ternary conditional operator a?b:c

#### Swift Assignment Operator

```
let fromAmount = 100
let fxRate = 23.21
let toAmount = (Double)(fromAmount) * fxRate
print("the To Amount is \(toAmount)")
//the To Amount is 2321.0

let (position,salary) = ("Project Manager",121000)
print("position is \(position)")
//position is Project Manager

print("salary is \(salary)")
//salary is 121000
```

#### Swift Arithmetic Operator

```
/*
*/
print(2000+3000)    //prints "5000"
print(3000-2000)    //prints "1000"
print(20*30)        //prints "600"
print(30/20)        //prints "1"
print((Double) (30)/(Double) (20)) //prints "1.5"
print("Hello" + "World")            //prints "HelloWorld"

```

#### Swift Remainder Operators, Also known as the modulo operator

```        print(100%3)// Returns the value that is left over
//prints "1"

print(-100%19)
//prints "-5"
```

#### Swift Floating point remainder Operator

```        print(100%3.14)
//prints "2.66"
```

#### Swift Increment and Decrement Operator

```
var age = 10
age++
print (age) //prints 11

++age
print(age) //prints 12

age += 10
print(age) //prints 22
```

#### Swift Pre and Post increment nuances

```        var year = 2015

//Pre Increment
let year1 = ++year
print("year = \(year) & year1 = \(year1)")
//prints "year = 2016 & year1 = 2016"

//Post Increment
let year2 = year++
print("year = \(year) & year2 = \(year2)")
//prints "year = 2017 & year2 = 2016"
```

#### Swift Unary Minus Operator

```
let delta = 10
let negativeDelta = -delta
let positiveDelta  = -negativeDelta
print("negative delta = \(negativeDelta) & postive delta = \(positiveDelta)")
//prints "negative delta = -10 & postive delta = 10"
```

#### Swift Unary Plus Operator

```        let kelvin = -180
let positiveTemp = +kelvin
print("In kelvin = \(kelvin) & positive temp = \(positiveTemp)")
//prints "In kelvin = -180 & positive temp = -180"
```

#### Swift Compound Assignment Operator

```   var salary1 = 100
salary1 += 20
print("salary1 = \(salary1)")
//prints "salary1 = 120"
```

#### Swift Comparison Operator

```        /*
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)”
Identity operators (=== and !==), which we use to test whether two object references both refer to the same object instance
Each of the above comparison operator returns a bool value
*/
let distance1 = 10.43
let distance2 = 12.32
print(distance1 == distance2)   //false
print(distance1 != distance2)   //true
print(distance1 > distance2)    //false
print(distance1 < distance2)    //true
print(distance1 >= distance2)   //false
print(distance1 <= distance2)   //true

let message1 = "Hello World"
let message2 = "Hello World"

print(message1 == message2)     //true
print(message1 != message2)     //false

```

#### Swift Ternary Conditional Operators

```
let initialMessage = "Hello John! "
let dateOfJoining = 2004
let finalMessage = initialMessage + (dateOfJoining == 2004 ? "Congratulations on Completing 10 Years":"You have a couple of years to complete a decade with xyz corp")
print ("finalMessage = \(finalMessage)")
//prints "finalMessage = Hello John! Congratulations on Completing 10 Years"

```

#### Swift Nil Coalescing Operators

```        /*
The nil coalescing operator a??b unwraps an optional a if it contains a value or returns a default value b if a is nil
The expression a is always of type optional
*/

let defaultTableColumnWidth = 100.0
var userDefinedTableColumnWidth: Double?
print("userDefinedTableColumnWidth = \(userDefinedTableColumnWidth)")
//prints "userDefinedTableColumnWidth = nil"

let columnWidthToBeUsed = userDefinedTableColumnWidth ?? defaultTableColumnWidth
print("column width to be used in the screen is = \(columnWidthToBeUsed)")
//prints "column width to be used in the screen is = 100.0"

userDefinedTableColumnWidth = 200.0
let newColumnWidthToBeUsed = userDefinedTableColumnWidth ?? defaultTableColumnWidth
print("column width to be used in the screen is = \(newColumnWidthToBeUsed)")
//prints "column width to be used in the screen is = 200.0"

```

#### Swift Closed Range Operators

```        //(x...y) ranges from x to y and includes both x and y
for i in 1...3{
print ("i=\(i)")
}
/*
i=1
i=2
i=3
*/
```

#### Swift Half Open Range Operator

```
(legalAge && hasClearedDriveTest == true)
{
print("John is allowed to drive")
}
else{
print("John can not drive")
}
//prints "John is allowed to drive"
//For a logical AND Operator to be true both the values needs to be true
//If one or both are false, then the output of the logical AND operator will be false

```

#### Swift Logical OR Operator

```        //In case of Logical OR Operator is one or both the values are true the result is true. the only condition the output will be false is when both the values are false
if (3>2 || 2>3){
print("One condition is true here and thus the result is true")
}
//Prints "One condition is true here and thus the result is true"

if (2>3 || 3>4){
print("this should not get executed")
}
else{
print("both the coditions are false")
}
```

#### Swift Combining Logical Operators

```
//The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first

let hasSuperUserAccess = false
let hasAccessToStatedScreen = true
let hasApplicationAccess = true
if hasApplicationAccess && hasAccessToStatedScreen || hasAdminAccess || hasSuperUserAccess {
print("the user can log in to the application and access the stated screen")
}
else{
print("the user should not be allowed access")
}
//prints "the user can log in to the application and access the stated screen"

//Explicit Parantheses
//Explicit Paranthese are used to make a complex expression easier to read
//Here what we want to enforce is that the user must have application access and should also have access to the stated screen or another way to use the screens/app is if the user has admin or super user access
if (hasApplicationAccess && hasAccessToStatedScreen) || hasAdminAccess || hasSuperUserAccess {
print("the user can log in to the application and access the stated screen")
}
else{
print("the user should not be allowed access")
}
//prints "the user can log in to the application and access the stated screen"
```
Posted in Swift Tagged with: , , ,