Increment and decrement

A common operation that you will need is to be able to increment or decrement a variable. In Swift, this is achieved like so:

var counter: Int = 0

counter += 1

// counter = 1

counter -= 1

// counter = 0

The counter variable begins as 0. The increment sets its value to 1, and then the decrement sets its value back to 0.

These operators are similar to the assignment operator (=), except they also perform an addition or subtraction. They take the current value of the variable, add or subtract the given value and assign the result to the variable.

In other words, the code above is shorthand for the following:

var counter: Int = 0 counter = counter + 1 counter = counter - 1

Similarly, the *= and /= operators do the equivalent for multiplication and division, respectively:

var counter: Int = 10

counter = 3 // same as counter = counter 3

// counter = 30

counter /= 2 // same as counter = counter / 2

// counter = 15

results matching ""

    No results matching ""