Swift Assignment Operators Tutorial 📝

beginner
21 min

Swift Assignment Operators Tutorial 📝

Welcome back to CodeYourCraft! Today, we're going to dive into the world of Swift Assignment Operators. These operators are essential tools in our Swift programming arsenal, helping us assign and modify values with ease. 🎯

What are Assignment Operators? 💡

Assignment operators are special symbols used in Swift to assign values to variables and constants, and to update the values of variables. They are a convenient way to perform an operation and store its result in a variable, all in one line of code.

Basic Assignment Operator (=) 📝

The most fundamental assignment operator is the equal sign (=). It assigns the value on its right side to the variable or constant on its left side.

swift
var myNumber: Int = 0 myNumber = 10 // myNumber now equals 10

Shorthand Assignment Operators 💡

Swift provides several shorthand assignment operators to make our code cleaner and more readable. Here are some examples:

Addition Assignment (+=) 📝

The addition assignment operator (+=) adds a value to the existing value of a variable and then assigns the result back to the variable.

swift
var myNumber: Int = 0 myNumber += 10 // myNumber now equals 10 (originally 0, then 10 added)

Subtraction Assignment (-=) 📝

The subtraction assignment operator (-=) subtracts a value from the existing value of a variable and then assigns the result back to the variable.

swift
var myNumber: Int = 10 myNumber -= 5 // myNumber now equals 5 (originally 10, then 5 subtracted)

Multiplication Assignment (*=) 📝

The multiplication assignment operator (*=) multiplies a value by the existing value of a variable and then assigns the result back to the variable.

swift
var myNumber: Int = 2 myNumber *= 3 // myNumber now equals 6 (originally 2, then 2 multiplied by 3)

Division Assignment (/=) 📝

The division assignment operator (/=) divides a variable's value by another value and then assigns the result back to the variable.

swift
var myNumber: Int = 12 myNumber /= 2 // myNumber now equals 6 (originally 12, then divided by 2)

Modulus Assignment (%) 📝

The modulus assignment operator (%=) calculates the remainder of a division operation and assigns the result back to the variable.

swift
var myNumber: Int = 10 myNumber %= 3 // myNumber now equals 1 (originally 10, then modulus 3)

Quiz 💡

Quick Quiz
Question 1 of 1

What does the addition assignment operator do?

That's it for today! Practice using these assignment operators in your Swift projects to make your code more efficient and readable. See you in the next lesson! 🎯