Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Declare Constants in Swift
Written by Team Kodeco

In Swift, constants are values that cannot be changed after they are set. This is in contrast to variables, which can be reassigned new values at any time.

To declare a constant in Swift, use the let keyword, followed by the constant name and an equal sign. For example:

let numberOfApples = 5

In this example, numberOfApples is a constant that has been set to the value of 5.

You can also declare constants with explicit type annotations. For example:

let message: String = "Hello, World!"

In this example, message is a constant of type String that has been set to the value “Hello, World!”.

It’s important to note that once a constant is set, it cannot be changed. For example, the following code would result in a compile-time error:

let numberOfApples = 5
numberOfApples = 6  // This will throw an error

An analogy to understand the concept of constants is to think of them as something written in stone, once it’s set it cannot be altered or changed.

© 2024 Kodeco Inc.