Swift Variables
Job-ready Online Courses: Click, Learn, Succeed, Start Now!
Variables store and manage data during program execution. They act as placeholders.
A variable can hold different types of values, such as numbers, text, or collections. It allows us to manipulate data, perform calculations, and make decisions based on the stored information. In this article, we’ll dive into how we use it and important points to consider while using them.
Declaration
Variables are declared using the var keyword, followed by their name and data type. Following is the syntax to declare a variable in Swift.
var variableName: dataType
Swift is a statically typed language. This means the data type of a variable is explicitly defined. We cannot change it after its declaration.
Initialization and reassignment of values
To store a value in a variable, we need to initialize it. This means we give an initial value to it.
var variableExample: String = "DataFlair"
Once we declare and initialize a variable, we can also reassign a value to it.
var variableName: String = "Swift" //declaring and initializing variable print(variableName) variableName = "DataFlair" //reassigning a value to variable print(variableName)
Output:
Swift
DataFlair
Naming Variables
- It should begin with an alphabet (A-Z or a-z) or underscore (_).
- It may contain letters or numbers or underscore.
- Other symbols or characters like ! @, #, etc., are not allowed.
- Swift is a case-sensitive language. So, dataFlair, and DataFlair are different.
// valid variables var DataFlair var dataFlair var _dataFlair //Invalid variables var 1dataFlair var DataFlair# var _DataFlair@
Data Types & Type Inference
Swift provides a rich set of data types that allow us to work with various kinds of data. Some of the data types used in Swift are:
Integers: Used to represent whole numbers.
var year: Int = 2023
Float: Used to represent numbers with a fractional component. (~6 decimal digits)
var temperature: Float = 25.8
Double: Used to represent numbers with a fractional component. (~15 decimal digits)
var pi: Float= 3.141592653589793
String: stores a sequence of characters.
var example: String = "DataFlair"
Character: represents individual textual elements.
var example: Character = "D"
Booleans: stores true or false values.
var isWeekend: Bool = false
Arrays: Used to store a collection of values of the same type.
var arrayExample: [String] = ["DataFlair", "Swift", "Data Types", "Array"]
Dictionaries: Used to store key-value pairs.
var dictionaryExample: [String: Int] = ["DataFlair": 1, "Swift": 5]
Tuples: Used to group multiple values of different types.
var tupleExample: (String, String) = ("DataFlair", "Tuples")
Optional: Used to handle the absence of a value.
var phoneNumber: Int? = nil
Custom Types: You can also create your own custom data types using struct, enum, or class.
Swift has a type inference system that can deduce the data type of a variable based on its initial value. We can omit the type annotation during declaration, and Swift will infer the type for us.
Type Annotation
Type annotations allow us to specify the data type of a variable. This feature enhances code clarity. It helps catch type-related errors during compile-time. It also aids in better code documentation. The syntax for type annotation involves using a colon (:) followed by the desired data type.
var name: String
Type annotations play a crucial role in the type inference mechanism. When Swift can’t determine a type automatically, annotations guide the compiler, avoiding ambiguity and ensuring the correct type deduction.
Printing Variables
Printing variables are used to display information to users, logging or debugging. We can print variables using the “print” function or string interpolation.
For instance:
var name: String = "DataFlair" print(name)
Output:
DataFlair
We can also embed variables directly within a string using string interpolation. It becomes easy to format and display variable values alongside text.
var name: String = "DataFlair" print( "Name: \(name)")
Output:
Name: DataFlair
We use debugPrint to investigate objects, custom classes, or structs more thoroughly. It provides a detailed representation of the data and their relationships. We use debugPrint primarily for debugging purposes.
var name: String = "DataFlair" debugPrint( "Name: \(name)")
Output:
“Name: DataFlair”
In the above example, we could also use print to achieve the same result. However, debugPrint provides additional formatting and includes quotation marks around the printed string. This can be helpful to distinguish printed values from other outputs during debugging.
Variable Scope
In Swift, variables have a specific scope. The scope determines where the variable is accessible and where can use it. There are two types of variable scope in Swift: Global Scope and Local Scope.
Global Scope
Variables declared outside the context of any function or block have global scope. This means we can access it from any part of the code in the same file. We initialize the global variables once. It persists throughout the lifetime of the application.
Local Scope
Variables within a function or block have a local scope. This means we can access it within that particular function or block only. Local variables are instantiated in memory at runtime when the function or block is invoked. They are deallocated when the execution of the function or block is completed.
The following examples depict the usage of local and global scope:
var globalVariable = "DataFlair" //declaration of global variable
func scopeFunction() {
var localVariable = "Scope" //declaration of local variable
print(localVariable)
}
print(globalVariable) //Output: DataFlair
scopeFunction() //Output: Scope
Output:
DataFlair Scope
Accessing a local variable out of its scope will lead to error.
func scopeFunction() {
var localVariable = "Scope" //declaration of local variable
print(localVariable)
}
print(localVariable)
Output:
Error: cannot find ‘localVariable’ in scope
print(localVariable) ^~~~~~~~~~~~~
Conclusion
Variables are essential building blocks in programming. It allows us to store, manipulate, and process data in our applications. This article depicts how to declare variables, how to initialize or assign values to them, how to name them, how to use different data types, how to leverage type inference, and how to manage variable scope. With this knowledge of variables, we can create powerful, data-driven Swift applications!
Did you like this article? If Yes, please give DataFlair 5 Stars on Google

