Swift Constant



Swift Programming Language By Knownion



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:

let siteName:String
print(siteName)

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:

let siteName:String  
siteName = "knownion.com"  
print(siteName)

Or

let siteName:String = "knownion.com"  
print(siteName)

Output:

knownion.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:

let siteName = "knownion.com"  
print(siteName)

Output:

knownion.com 



Post a Comment