Education
Software Development Executive - II
Last updated onJul 10, 2024
Last updated onMay 13, 2024
Welcome, in today’s blog, we will embark on an enlightening journey into the world of Swift.
A major focus will be on understanding Swift variables. Variables are essential in almost all programming languages and Swift is no exception.
In the simplest of terms, variables in Swift are used to store values that can be changed or manipulated as we run our programs. Understanding variables is foundational to coding in Swift. They are the holders of the various data types that your program will interact with. In Swift, variables can hold a range of types – from integers, strings, and arrays to more complex custom types.
Swift also gives us fantastic flexibility when it comes to naming our variables. Variable names in Swift can contain almost any character including Unicode characters. For instance, the var name can be as simple as var age = 21 or as complex as var π = 3.14159. This ensures that our source code is clean, understandable, and accommodating of various natural languages.
Here’s an example using a simple var "helloWorld":
1var helloWorld = "Hello, world!"
The var keyword is used in Swift for variable declaration. Its syntax is very straightforward. First, you start with the var keyword, followed by the name of the variable which is written either as a letter or a sequence of characters. Last is an equal sign which assigns the initial value to the variable. Additionally, Swift has a strong regard for type safety. For instance, if a variable is declared as an Int type, you cannot assign a type string to it later.
Here’s an example of variable declaration using the var keyword:
1var var_1_VariableDeclaration: Int 2var_1_VariableDeclaration = 100
It’s important to give your variables an identifying name that describes the value they're going to store. In the example above, we have declared a variable called var_1_VariableDeclaration which stores integer values. Also, remember that Swift is case-sensitive. So, var_1_VariableDeclaration is different from say VAR_1_VariableDeclaration.
The naming of constant and variable names in Swift is an extensive area. It is not only important to name variables correctly, but also to adhere to the conventions of Swift. In Swift, identifiers (be they constant or variable names) can't contain whitespace characters, mathematical symbols, arrows, Private-use (or invalid) Unicode scalar values, line- and box-drawing characters.
However, it can start with an underscore character (_), lowercase letters, uppercase letters, or can also include some special characters like dollar sign ($), question mark (?), and exclamation mark (!).
1let marcaDelCarro = "Toyota" 2var edadDelUsuario = 21, nombreDelUsuario = "Juan"
In the above example, two variables and one constant are declared. Pay attention to the use of lowercase letters and CamelCase for multiple-word variable names. CamelCase makes code easier to read and understand.
Swift has several basic types of values that variables can store.
Integer literals and floating-point literals represent numbers. Integers store numbers without a fractional component, while floating-point numbers can. Type string represents text. Swift also provides a Boolean type (Bool), which can be either true or false. Boolean variables are often used in conditional test expressions.
Here are some examples:
1var myString: String = "I am a string" 2var myInteger: Int = 1 3var varValue: Double = 145.33 4var isSunnyToday: Bool = true 5var pi = 3.14159 // infer as Double
In the examples above, myString is an example of a type string, myInteger is an integer literal, and varValue is a floating-point literal. The variable isSunnyToday is a boolean variable with an initial value of true. The use of values and variables like this makes Swift easier to read and more flexible.
Swift variables must be given initial values before they can be used. This is to avoid unexpected behavior in the program. However, Swift has another type of variable that can have no value - either through being not set or by being set to a special value 'nil'. These are called Optional variables.
For instance, an initial value can be added at the time of variable declaration:
1var age = 28
In the code snippet above, we're declaring a new variable called age and giving it a new value of 28. Swift uses type inference to detect that 28 is an integer value, so the age variable will be treated as an Int type.
However, what if we don't want to give the variable a value initially? This is where the concept of Optionals comes in. Optionals are a language feature in Swift that allows a variable to be either a value or nil.
1var age: Int? = nil
In the code above, we declare an Optional variable age and set its value to nil. Now, we are free to assign a value to age at any point in our code, or we can leave it as nil.
The var keyword is a critical part of working with variables in Swift. By prefixing a variable name with var, Swift understands that the variable value can be changed after it has been assigned. This is unlike constant values (that are signified using the let keyword), which cannot be changed after their initial assignment.
Here is a simple example of var in action:
1var friendlyWelcome = "Hello!" 2friendlyWelcome = "Bonjour!"
Initially, friendlyWelcome is assigned the value "Hello!". However, the var value is later changed to "Bonjour!". Since friendlyWelcome is a variable, this type of modification is allowed.
In Swift, you can choose to declare multiple variables in a single line of code. This can greatly clean up the source code and make it more concise. Here’s an example:
1var x = 0.0, y = 0.0, z = 0.0
In the above example, we have declared multiple variables x, y, and z, and assigned all of them the value 0.0. This is a convenient and concise way of variable declaration when variables of the same type need to be declared.
In Swift playbook, var and let play important roles; however, they are used in different scenarios. A summary is: var allows changes after the declaration, whereas let does not. In other words, var is mutable while let is immutable.
Here’s an example using both var and let:
1var var1 = "Swift" 2var1 = "Swift Programming" 3 4let let1 = "Swift" 5let1 = "Swift Programming" //this line will make a `compile time error`
In the above example, assigning a new value to var1 is perfect because it's a var. However, attempting to assign a new value to let1 will result in a compile-time error, because it's a constant (let) and its value cannot be changed.
Tuples are a simple and convenient way to group multiple variables without having to create a complex type. They're very useful if you want to return multiple values from a function.
Here’s how to define a tuple:
1var person = (24, "John")
In the above example, we declare a variable person which is a tuple containing two values (an integer and a string). We can access the values of a tuple using index numbers starting with 0:
1print(person.0) //Output: 24 2print(person.1) //Output: John
You can also give each element in a tuple a name, which can be used to initialize a new value or access its existing value:
1var person = (age: 24, name: "John") 2print(person.age) 3print(person.name)
With Swift, you can define an alternative name for an existing type using typealias. After a type alias is defined, the aliased name can be used instead of the existing type throughout the program.
Here's an example. Suppose you are repeatedly using [String, Int, Double] in your code. You could clear this up using a type alias:
1typealias PersonInfo = (name: String, age: Int, height: Double) 2var john: PersonInfo = ("John", 24, 180.5)
In the code example above, PersonInfo is an alternative name for the tuple type (name: String, age: Int, height: Double). It makes the code more readable and easier to manage.
Swift supports most of the standard C operators and improves several capabilities to remove common coding errors. Swift operators don't allow values to overflow by default. You can opt-in to value overflow behavior by using Swift’s overflow operators.
There are different numerical operators available in Swift like + for adding together variables, - for subtracting one variable from another, * for multiplying variable, and / for dividing one variable by another.
Let’s consider an example:
1var a = 42 2let b = 10 3 4print("a + b = \(a + b)") // Adding two variables 5print("a - b = \(a - b)") // Subtracting one variable from another 6print("a * b = \(a * b)") // Multiplying variables 7print("a / b = \(a / b)") // Dividing one variable by another
A variable's scope is the context in which the variable is defined. Any variables created inside a function, for example, can't be used outside of that function because they're local to that function. This protects the variables from being accessed inadvertently from other parts of your program, and also lets you reuse variable names in different scopes.
Example:
1func greet() { 2 var name = "Alice" // 'name' variable can only be used inside this function 3 print("Hello, \(name)!") 4} 5 6var name = "Bob" // This 'name' variable is different from the one inside the greet function 7print("Hello, \(name)!") 8greet()
The output of the above code snippet would be:
1Hello, Bob! 2Hello, Alice!
Understanding the concept of variables is key to any programming language and Swift is no different.
• Swift variables are strongly typed which means the compiler infers the type of value it can store.
• Swift variables are declared using the var keyword. For example, var name = "John".
• Constants are declared using the let keyword. For example, let name = "John".
• Optionals variable in Swift is a type that can hold either a value or no value(nil).
• var in Swift can store values that can be changed later in the program, whereas let is used for constant values that cannot be changed.
• Swift allows for multiple variable declarations in a single line.
• A tuple is a group of values encapsulated into a single compound value.
• A type alias allows you to provide a new name for an existing data type.
And that brings us to the end of the blog on "Understanding Swift Variables". We hope you now have a deeper knowledge of what Swift variables are and how to use them. Remember, the best way to get comfortable with these concepts is through practice. So, get set and start coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.