Swift Assignment Operators

Swift Assignment Operators

Use = to assign a value.

Compound assignment operators like +=-=*= and /= update a variable in place.


Compound Assignment

Use compound operators like += and *= to update a variable in place.

Example

var total = 10
total += 5
print(total)
total -= 3
print(total)
total *= 2
print(total)
total /= 4
print(total)

This example shows updating a variable with compound assignment operators.



Append to String

You can also use += with strings to append text to a mutable string variable.

Example

var s = "Hello"
s += ", Swift"
print(s)

This example appends to a string in place with +=.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *