Swift let keyword

Swift let keyword is used to define a constant in Swift programming.

A swift constant is immutable. A swift constant once initialized cannot be modified.

In this tutorial, we will learn how to use let keyword to define a constant in Swift, and its immutable behaviour.

Example

In the following example, we will define a constant in Swift using let keyword, and print it to the console.

main.swift

let x = 10
print(x)

Output

Swift let keyword example

Now, let us try to modify a constant in Swift. We get an error with the message Cannot assign to value: 'x' is a 'let' constant, also with a suggestion Change 'let' to 'var' to make it mutable.

Swift let keyword - try to modify constant in Swift

Since, the constant is immutable, we cannot update its value.

Conclusion

In this Swift Tutorial, we learned about let keyword in Swift, and how to define a constant in Swift using let keyword.