Welcome to our Swift Programming Tutorial series! Here, we will explain every Swift topic step-by-step with both theory and practical examples. Every concept will be broken down point-by-point, ensuring you can easily understand and develop your skills effectively. Whether you are a complete beginner or at the intermediate level, in this tutorial series, you will get clear explanations, real-life examples, and practical exercises that will help you learn Swift programming confidently.
We will cover all topics from beginner to advanced, so no matter where you are in your learning journey, you’ll find something valuable here.
In Part 1, we will build your foundation by diving into the basics of Swift:
Variables and Constants in Swift (var, let)
Variables
In Swift, we use the var
keyword when we need to store a value that can change later. This allows us to update the value of the variable whenever needed.
// Using 'var' to declare a variable
var name = "Joey" // We have assigned the 'name' Joey, which can be changed.
print(name) // Output: Joey
// Changing the value of 'name'
name = "Ross"
print(name) // Output: Ross
var name =
“Joey”: We assigned the value joey
to the variable age
. Initially, name
is joey.
name = "Ross"
: Later, we updated the value of name
to Ross
. Since name
is a variable (declared with var
), we can change its value.
Constants
On the other hand, we use let
when we need to store a value that will not change. Once a constant is assigned a value, it cannot be modified throughout the program.
// Using 'let' to declare a constant
let year = 2001 // year is fixed, we cannot change it
print(year) // Output: 2001
// Trying to change the value of 'year' will result in an error
year = 1995
// Error: Cannot assign to value: 'year' is a 'let' constant
let year = 2001
: We set the constant year
to 2001. This value can’t be changed later. If we try to change it, Swift will show an error because constants can’t be modified.
Data Types in Swift
Int (Integer)
We use it to store whole numbers (without decimal points).
Example: 2, -15, 40
// Declaring an integer variable
var value: Int = 30
print(value) // Output: 25
Double
We use it to store floating-point numbers, i.e. numbers that have decimal values.
Example: 3.14, -0.95, 105.01
// Declaring a double variable
var price: Double =23.55
print(price) // Output: 23.55
Float
Float is used to store numbers with decimals, just like Double, but it’s less accurate. It’s useful when you need to save memory or don’t need high accuracy.
// Declaring a float variable
var temp: Float = 32.5
print(temp) // Output: 32.5
String
Strings are used to store text values, such as names, addresses, etc. Example: “Hey”, “Inspire The Dev”
// Declaring a string variable
var greet: String = "Hello, Inspire The Dev!"
print(greet) // Output: Hello, Inspire The Dev!
Bool
Bool
is used to store true or false values. It’s typically used for making decisions in your code, like checking if a condition is true or false.
// Declaring a boolean variable
var swiftIsFun: Bool = true
print(swiftIsFun) // Output: true
Character
Character
refers to a type that represents a single character from a string. A Character
is a value type that can be a single Unicode scalar, which may include letters, digits, symbols, or even emoji.
// Declaring a character variable
var keyword: Character = "A"
print(keyword) // Output: A
Type Inference vs Explicit Type Declaration
Type Inference
Swift automatically detects the type of the value you assign to a variable or constant.
var number = 25 // Type inferred as Int
Explicit Type
Inference
You can declare the type explicitly if you want to be sure what type the variable is.
var name: String = "Inspire"
Control Flow in Swift
Control flow means how we will control our code. That means, when which code will run and on what condition – we define all this through control flow. In Swift, we can do this in many ways like if-else, switch statements, and loops.
Today we will understand all these concepts and see them with practical examples. Let’s start!
Conditional Statements: If-Else
Conditional statements are used when we have to execute our code based on a condition. Meaning, if a condition is true then one block will run, and if it is false then another block will run.
If Statement
We use the if statement when we have to execute the code after checking a condition.
let marks = 90
if marks >= 90 {
print("you were selected") // Output: you were selected
}
If-Else Statement
If we want to provide an alternative action when the condition is false, we use else.
let marks = 70
if age >= 90 {
print("You were selected")
} else {
print("Sorry!, You were not selected") // Output: Sorry!, You were not selected
}
If-Else If-Else Statement
If you need to check multiple conditions, you can use else if.
let marks = 45
if marks >= 90 {
print("You were selected")
} else if marks >= 50 {
print("You were not selected")
} else {
print("Please try again")
} // output : Please try again because this condition not go in if and else if statment that why print else condition
Switch Statement
If you need to match a single value with multiple conditions, then you use a switch statement. In a switch statement, you compare a single value with multiple cases.
let fruit = "Apple"
switch fruit {
case "Banana":
print("Yellow fruit")
case "Apple":
print("Red ya Green fruit") // Output: Red ya Green fruit
case "Orange":
print("Orange fruit")
default:
print("Unknown fruit")
}
Multiple Patterns in a Case
If you need to match multiple values in a single case, you can combine them with commas.
let fruit = "Apple"
switch fruit {
case "Apple", "Banana":
print("Popular fruit") // Output: Popular fruit
default:
print("WaterMelon")
}
Range Matching in Switch
You can also match ranges in the switch, which is a very powerful feature.
let score = 85
switch score {
case 90...100:
print("Grade: A")
case 80..<90:
print("Grade: B") // Output: Grade: B
case 70..<80:
print("Grade: C")
default:
print("Grade: D")
} // 80..<90: Match, since 85 is between 80 and 89.
Loops in Swift
Loops are used when we want to repeat the same code multiple times. There are two types of loops in Swift:
For-in Loop
If you want to iterate over the elements of a collection (array, dictionary, or range), you use a for-in loop.
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
print(number) // Output: 1 2 3 4 5
}
For-in Loop with Ranges
You can also use a for-in loop with ranges.
for i in 1...5 {
print(i) // Output: 1 2 3 4 5
}
While Loop
The while loop will run as long as the specified condition is true.
var counter = 0
while counter < 5 {
print(counter) // Output: 0 1 2 3 4
counter += 1
}
Repeat-while Loop
The repeat-while loop works just like a while loop, but it checks the condition after the loop. This means that the code block will run at least once, whether the condition is true or not.
var counter = 0
repeat {
print(counter) // Output: 0 1 2 3 4
counter += 1
} while counter < 5
Function
A function is a block of code that performs a specific task. When you need to perform a task repeatedly, you can define that task as a function and call it whenever you want. A function is made up of a name, parameters (optional), and return value (optional).
func functionName(parameters) -> returnType {
// Function body (code to be executed)
}
- func: Keyword that tells that you are defining a function.
- functionName: This is the name of the function, which you have to use while calling the function.
- parameters: These are the values that are passed inside the function (optional).
- -> returnType: If the function returns a value, then that type is specified here (optional).
- Function body: This is the code that is executed inside the function.
Function Without Parameters and Return Value
Let’s look at a simple function that neither takes any parameters nor returns any return value. We use it only to perform some task.
func greet() {
print("Hello, welcome to Swift programming!")
}
greet() // Output: Hello, welcome to Swift programming!
Function with Parameters
If you want to make your function dynamic, meaning you have to pass some inputs, then you can give parameters to the function. Parameters are the values that you pass when you call the function.
func greetUser(name: String) {
print("Hello, \(name)! Welcome to Swift programming!")
}
greetUser(name: "Raj") // Output: Hello, Raj! Welcome to Swift programming!
Here, we have created greetUser(name:) function which takes a parameter name. When we call greetUser(name: “Raj”), the function will print “Raj” in the greeting message.
Function with Return Value
If your function returns a value, then after the function you have to specify -> returnType, where returnType is the type that the function will return (like Int, String, Bool, etc.).
func addNumbers(a: Int, b: Int) -> Int {
return a + b
}
let sum = addNumbers(a: 10, b: 20)
print(sum) // Output: 30
Here, the addNumbers(a:b:) function takes two integers a and b, sums them and returns the result. We have written -> Int, which indicates that the function will return an integer value.
Function with Multiple Parameters
You can pass as many parameters as you want to your function. Multiple parameters are used when you need to pass more than one input.
func calculateArea(length: Int, width: Int) -> Int {
return length * width
}
let area = calculateArea(length: 5, width: 10)
print(area) // Output: 50
Here, the calculator(length:width:) function takes two parameters, length and width, and returns their product.
Function Overloading
In Swift you can use function overloading, which means you can create multiple functions with the same function name, which work with different parameters.
func greet(name: String) {
print("Hello, \(name)!")
}
func greet(age: Int) {
print("Hello, you are \(age) years old!")
}
greet(name: "Raj") // Output: Hello, Raj!
greet(age: 25) // Output: Hello, you are 25 years old!
Here, we have created two greet functions – one that takes a parameter of String type (name), and one that takes a parameter of Int type (age). Both these functions are overloaded because they have the same name but different parameters.
Optional
Optional is a type that gives the option to make a variable nil or hold a valid value. Meaning, you are storing some value, but it is possible that that value may not be there, and optional is used to handle this situation.
var number: Int?
Here number is an optional integer. Meaning number can be either an integer value or nil.
var age: Int? // 'age' is now optional, so it can hold a value or nil
age = 25 // Now 'age' has been assigned a value
print(age) // Output: Optional(25)
Here, age is declared as optional integer. When we print age, it will show Optional(25) because age is optional and it is holding a value.
Why Use Optionals?
Optionals are used in situations where you do not know whether a variable will get a value or not. If you have the possibility of not getting a value, then you can make that variable optional.
Optional Binding
Optional Binding is used when we need to safely unwrap an optional value. This means that we check whether the optional variable has any value or not, and if it does, then we safely access that value.
var age: Int? = 25
if let originalAge = age {
print("User's age is \(originalAge)") // Output: User's age is 25
} else {
print("Age is not available")
}
Here, age is optional. If we unwrap age safely using let. If we get a value, it is assigned to the originalAge variable and we are able to print. If age is nil, the else block is executed.
Forced Unwrapping
If you are sure that the optional variable is not nil, you can access that value directly by forced unwrapping. Its syntax is !.
Important: Use forced unwrapping only when you are 100% sure that the value is available in the optional variable, otherwise your code may crash.
var age: Int? = 25
print(age!) // Output: 25
Here with forward! we have done forced unwrapping, and accessed the value directly. If forward was nil, it would have given an error in the sequence.
Nil Coalescing Operator
If you need to safely unwrap the optional value and provide a default value if it is nil, you can use the nil coalescing operator (??).
let value = optionalValue ?? defaultValue
// code
let number: Int?
let value = number ?? 30
print(value) // output 30
- Optional we can handle nil values as well.
- Optional Binding we can safely unwrap values.
- Forced Unwrapping when you are sure that the value is available.
- Nil Coalescing Operator we can assign default values.
Conclusion
In Part 1 of our Swift programming journey, we laid a solid foundation by covering key concepts like Variables and Constants, Data Types, Type Inference vs Explicit Type, Control Flow, Loops, Functions, and Optionals. These core topics help you write safe, efficient, and organized Swift code — essential for everyday development.
Now, as we move into Part 2, we’re taking a step further into the more advanced and powerful features of Swift! 🚀 Closure, Protocol, Extension, Error Handling.
In this part, we’ll unlock some game-changing tools that every Swift developer needs to know to build scalable, robust, and flexible applications:
Leave a Reply