Swift programming for Beginners – Swift Variables, Constants and Literals

(Swift for Beginners)

Swift Variables, Constants and Literals

 

In this article, you will learn about variables, constants, literals and their use cases in Swift programming.

What is a Variable?

In programming, variables are used to store data in memory which can be used throughout the program. Each variable must be given a unique name called identifier. It is helpful to think of variables as containers that hold information which can be changed later.

Non technically, you can think of a variable as a bag to store some books in it and those books can be replaced with other books later.


How to declare variables in Swift?

In Swift, we use var keyword to declare a variable.

Example:

var siteName:String
print(siteName)

We have declared a variable named siteName of type String, which means it can only hold string values. Visit Swift Strings to learn more about strings.

If you try to run the above code in playground, it will give us compile time error (variable is used before initialized) because it does not store/contain any values.


How to assign value to a variable in Swift?

You can assign the value in a variable using the assignment operator (=).

Example 1: Declaring and assigning a value to a variable

var siteName:String
siteName = "Apple.com"
print(siteName)

OR

You can also assign the value inline as

var siteName:String = "Apple.com"
print(siteName)

When you run the program, the output will be:

Apple.com

The variable siteName now contains value “Apple.com”.


Since, Swift is a type inferred language, it can automatically infer (know) “Apple.com” is a String and declare siteName as a String. So, you can even remove the type (:String) from declaration as:

Example 2: Type inferred variable in Swift

var siteName = "Apple.com"
print(siteName)

When you run the program, the output will be:

Apple.com

Since, siteName is a variable, you can also change its value by simply using assignment operator but without var keyword as:

Example 3: Changing the value of a variable

var siteName = "Apple.com" 

// Assigning a new value to siteName
siteName = "Programiz.com"
print(siteName)

When you run the program, the output will be:

Programiz.com

What is a Constant?

A constant is a special type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later.

Non technically, you can think of constant as a bag to store some books and those books cannot be replaced once placed inside the bag.


How to declare a constant in Swift?

In Swift, we use let keyword to declare a variable.

Example:

let siteName:String
print(siteName)

We have declared a constant named siteName of type String.

If you try to run the above code, it will gives us compile time error (constant used before initialized) because it does not contain/hold any value.


How to assign value to a constant in Swift?

You can assign the value in a constant same as variable using the assignment operator (=).

Example 4: Declaring and assigning a value to a constant

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

OR

You can also assign the value inline as

let siteName:String = "Apple.com"

When you run the program, the output will be:

Apple.com

Now the constant siteName contains/holds value “Apple.com”.


Like variables, you can remove the type (:String) from declaration as:

Example 5: Type inferred constant in Swift

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

When you run the program, the output will be:

Apple.com

Example 6: Changing the value of constants (Not allowed)

let siteName = "Apple.com"
siteName = "Programiz.com" //compile time error
print(siteName) 

Above statement gives us an error because as we said the value of a constant cannot be changed once data is stored. This is the key difference between a variable and constant.


What is a Literal?

A literal is a value that appears directly in your source code. It can be a number, character, or a string etc. For e.g: “Hello, World” , 12, 23.0, “C” are simple example of literals. Literals are often used to initialize (assign values to) variables or constants.

For example:

let siteName = "Apple.com"

In the above expression siteName is a variable, and "Apple.com" is a literal.


Types of literals in Swift

Integer literals

It represents a decimal, binary, octal, or hexadecimal value. It has four types.

  • Binary Literals
    • Represents binary value.
    • Begins with 0b.
  • Octal Literals
    • Represents octal value.
    • Begins with 0o.
  • Hexadecimal Literals
    • Represents hexadecimal value.
    • Begins with 0x.
  • Decimal Literals
    • Represents decimal value.
    • Begins with nothing. Everything you declare in integer literal is of type decimal.

Example 7: How to use an integer literal in Swift?

let binaryNumber = 0b11111111
print(binaryNumber)
print(1231)

When you run the program, the output will be:

255
1231

In the above program, there are two integer literals 0b11111111 (binary literal) and 1231 (decimal literal). The decimal value of 11111111 is 255, therefore the print(binaryNumber) statement outputs 255 in the screen.

Similarly print(1231) outputs decimal value 255 in the console.


String & Character literals

A string literal is a sequence of characters surrounded by double quotes and a character literal is a single character surrounded by double quotes.

Example 8: How to use string and character literal in Swift?

let someCharacter:Character = "C"
let someString:String = "Swift is awesome"

In the above program "C" is a character literal and "Swift is awesome" is a string literal.


Floating point literals

It is used to initialize variables of data type float and double. It can be of two types:

Decimal:

It can have an optional exponent, indicated by an uppercase or lowercase e. For decimal numbers with an exponent of exp, the base number is multiplied by 10exp:

Example 9: How to use decimal literals in Swift?

let someFloat = 12.23
let someAnotherFloat = 3.14e2 
print(someFloat)
print(someAnotherFloat)

When you run the program, the output will be:

12.23
314.0

In the above program 12.23 and 3.14e2 are floating point literals. 3.14e2 is expressed with exponential and is equivalent to 3.14 * 102.

Hexadecimal:

Hexadecimal floats must have an exponent, indicated by an uppercase or lowercase p.For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp:

Example 10: How to use hexadecimal literals in Swift?

let someFloat = 0xFp10 
let someAnotherFloat = 0xFp-12
print(someFloat)
print(someAnotherFloat)

When you run the program, the output will be:

15360.0
0.003662109375

In the above program 0xFp10 and 0xFp-12 are floating point literals. 0xFp10 is expressed with exponential and equivalent to 15*210 (F is represented as 15 in decimal). Therefore, print(someFloat) outputs 15360.0 in the screen.

Likewise, 0xFp-12 is equivalent to 15 * 2-12. Therefore, print(someAnotherFloat) outputs 0.003662109375 in the screen.


Boolean Literals

There are two boolean literals in swift. They are true and false..

Example 11: How to use Boolean literals in Swift?

let result:Bool = false

In the above program, false is a Boolean literal which is assigned to the constant result.


Rules and Best practices for variables and constants

  1. Choose a name that makes sense. For example, var name makes more sense than var n.
  2. Use camelCase notation to declare a variable or a constant. Camel-case notation starts with lowercase letter. For example:
    var studentName
    let studentAge
    let address
    
  3. You can also define variables and constants without labeling it. Not labeling with name means you are not going to use it in the program. There are many cases where you want to create a unused variable. In that case you can use _ placeholder as:
    var _ = "Apple.com"//string initialized but not stored in a variable
    let _ = "Apple.com"

    Or even this is valid

    _ = "Apple.com"
  4. Use constants if you only need to set a value once and never need to change it again during a program. However, if you do need to change it at a later point, use variables.
  5. Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.Example:
    var 12 = "Apple.com" //gives a compile error: expected pattern
    var @hello = “Hello” //gives a compile error: expected pattern

     

Swift programming for Beginners – Swift Variables, Constants and Literals

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!