Home » Swift Constants

Swift Constants

As the name shows, constants are the special type of variables whose values can’t be changed. They are like containers which are stored permanently with some items.

How to declare Swift Constants?

The let keyword is used to declare a variable.

Example:

Here, we have declared a constant named siteName of type String. It can hold only string values. If you execute the above code, it will give a compile time error because we have only declared the constant and not assigned any value.

Let’s see how to assign values to a Swift constant.

How to assign values in Swift constant?

We can assign a value in Swift constant by using Assignment operator (=).

Example:

Or

Output:

tutoraspire.com   

As Swift is a type inferred language, you can remove the type (:String) from declaration and even it will show the correct result.

Example:

Output:

tutoraspire.com   

Note: You can’t change the value of the constant.


Next TopicSwift Literals

You may also like