Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Understand Variable Mutability in Swift
Written by Team Kodeco

In Swift, variables can be declared as either mutable or immutable. A mutable value can be reassigned a new value, while an immutable variables cannot.

To declare a variable as mutable, use the var keyword, followed by the variable name and an equal sign. For example:

var numberOfApples = 5
numberOfApples = 6

In this example, numberOfApples is a mutable variable that has been assigned the value of 5. It can be reassigned a new value of 6.

To declare a variable as immutable, use the let keyword, followed by the variable name and an equal sign. For example:

let message = "Hello, World!"
message = "Goodbye, World!"  // This will throw an error

In this example, message is an immutable variable that has been assigned the value “Hello, World!”. It cannot be reassigned a new value.

Should I Use Mutable or Immutable Varables?

In general, it is good practice to use immutable variables (constants with let) whenever possible, as they can help prevent unintended changes to your code and make it easier to reason about.

However, if you know that a variable needs to change, then of course you should use mutable variables (var).

© 2024 Kodeco Inc.