Chapter 19 : Incrementing and Decrementing Operators

Topics Covered :

1. What are Incrementing and Decrementing Operators
2. Pre-increment operator
3. Post-increment operator
4. Examples

Comparison Operators

Incrementing and Decrementing operators are Unary operators.

Incrementing Operators

Increment operator increases the value of its operand by 1.

The operand(variable) must be a integer value.

We have two types of Increment operator,

1. Pre-increment operator

++myVar (Pre-increment : Increments myVar by 1, then returns \$var)

2. Post-increment operator

myVar++ (Post-increment : Returns myVar, then increments \$var by one)

Example : Pre-increment operator

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Incrementing and Decrementing Operators in Swift
//
//  Created by Code2care on 16/09/14.
//

var i = 10

//Increments a by 1, then returns i
println(++i)

```
```
Output :

11
Program ended with exit code: 0

Example : Post-increment operator

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Incrementing and Decrementing Operators in Swift
//
//  Created by Code2care on 16/09/14.
//

var i = 10

//Returns i, then increments i by one
println(i++) // no increment
println(i++) //  increment by 1
```
```
Output :

10
11
Program ended with exit code: 0

Similarly we also have two types of Decremental Operator's,

1. Pre-decrement Operator

++myVar (Pre-decrement : Decrements myVar by 1, then returns myVar)

2. Post-decrement Operator

myVar++ (Post-decrement : Returns myVar, then decrements myVar by one)

Example : Pre-decrement operator

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Incrementing and Decrementing Operators in Swift
//
//  Created by Code2care on 16/09/14.
//

var i = 10

//Decrements i by 1, then returns i
println(--i)
```
```
Output :

9
Program ended with exit code: 0

Example : Post-decrement operator

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Incrementing and Decrementing Operators in Swift
//
//  Created by Code2care on 16/09/14.
//

//Returns i, then decrements i by one
println(i--)

println(i)

```
```
Output :

10
9
Program ended with exit code: 0