Assignment operators - Swift Tutorial

Ozan Emre Duran
AppleCode Chronicles
2 min readJun 6, 2023

Assignment Operator (=): The assignment operator is used to assign a value to a variable or constant. For example:

let x = 10 
var y = 5
y = x // y is now 10

Compound Assignment Operators: Compound assignment operators combine assignment with another operation. They perform the operation and assign the result back to the variable or constant. Some examples include:

  • Addition Assignment (+=):
var a = 5 
a += 3 // equivalent to a = a + 3, a is now 8
  • Subtraction Assignment (-=):
var b = 7 
b -= 4 // equivalent to b = b - 4, b is now 3
  • Multiplication Assignment (*=):
var c = 2 
c *= 5 // equivalent to c = c * 5, c is now 10
  • Division Assignment (/=):
var d = 12 
d /= 3 // equivalent to d = d / 3, d is now 4
  • Remainder Assignment (%=):
var e = 10 
e %= 3 // equivalent to e = e % 3, e is now 1

Nil-Coalescing Assignment Operator (??=): The nil-coalescing assignment operator assigns a value to a variable only if it is currently nil. It provides a convenient way to assign a default value when a variable is nil. Here’s an example:

var name: String? 
name ??= "John" // assigns "John" to name if it is nil

These are some of the assignment operators available in Swift. They allow you to assign values, perform operations, and update variables or constants in a concise manner.

If you’re interested in learning more about Swift, I recommend checking out my articles on Medium. You can access them through the template I created on Notion, which provides a structured learning process and easy navigation to different topics. Happy learning, and best of luck on your Swift programming journey!

Click here for Notion Swift Tutorial Template :)

--

--

Ozan Emre Duran
AppleCode Chronicles

I'm a passionate programmer who loves exploring and using Apple products. Swift is my language of choice.