Ad space (banner)
๐ŸฆSwift Lessons
Lesson 19 / 68

Constants (let, and why it matters)

In this lesson you will learn the role of let in Swift, so values that must not change are handled safely. This is for anyone searching for "Swift let constant how to use".

In Swift a value created with let cannot be changed afterwards. Such an unchanging value is called a constant, and Swift encourages using them freely to head off accidental-rewrite bugs.

The sample code defines a perfect score as a constant with let maxScore = 100 and uses it to build a message. Uncomment the maxScore = 200 line and you can watch it become a compile error.

A common stumbling block for beginners is deciding between let and var. The recommended approach is to try let first and switch to var only if you find you need it.

In real-world development, a value declared with let is checked at compile time, so an accidental rewrite is caught before the program ever runs - a basic part of what makes Swift safe.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)