Swift Constants Basics

Last time we talked about variables. A place to store or assign data . Another way to assign or store data is using constants.

Constants acts the same as variables with only key difference is that values can only be assigned once. It cannot be assigned another value again.

Constant Declaration

Using the the keyword “let” assign a data type.

let permanentString = "I am a permanent text"

Assigning another value after declaration will throw an error in Xcode — Cannot assign to value: ‘permanentString’ is a ‘let’ constant

permanent = "try to change me" 

Use constants when assigning values unless the value will change throughout your code, only then use variables. When a variable value is never changed you would get a warning from form Xcode to use constants instead.

Leave a Reply

Your email address will not be published.