2. Introduction to Swift Programming Language
Swift is the go-to language for developing applications on the iOS platform, including iPhone and iPad apps.
This article is for absolute beginners in the Swift language. It covers variables, conditionals, and functions. We’ll cover more topics of Swift in coming articles!
Hello, world!
Ah, this classic phrase, without which no introduction to a programming language is complete! In Swift, you just need to use the print
statement to print stuff.
print("Hello, world!")
Variables
We store values we might use later in program through variables. You can store integers, bools (true/false), strings (sequence of characters) and more.
All you need to do is use the keyword var
and then the name of the variable. After that you can use =
to assign a value or :
to define the type. By convention camelCase is used for naming variables
var age = 20
var name:String
name = "Ayesha"
print("I am \(name), my age is \(age)")
\()
are used in print statements to print the values stored in variables. This is called string interpolation. String interpolation allows you to embed variables or expressions directly into string literals.
For defining constants, we use the keyword let
Constants are variables which will be never changed in the code. Constants are particularly useful when the value is not supposed to change during the program execution.
let rollNumber = 13
Conditionals
Conditionals give us a way to define conditions over variables. If one condition is true, that block will be executed.
Say you want to print something according to a condition or do calculation based on whether certain aspects are met, then you’d use conditionals.
if-else
First, the if
condition is checked. If that condition is met, the code in its block is executed and all other conditions (else if and else) are skipped. Otherwise, all else if
conditions are checked and if none of them meets their respective conditions, the else
block is executed.
var age = 20
if age<16 {
print("You cannot get any type of driving license!")
}
else if age<18 {
print("You can get learner's license")
}
else {
print("You are eligible for a permanent driving license!")
}
Exercise for you: Age Classifier
- Create a variable
userAge
and assign it a value. - Write a conditional statement to classify the age into categories like “Child,” “Teenager,” “Adult,” or “Senior.”
- Print a message indicating the category based on the age.
Switch
It is a powerful and concise way to handle multiple cases compared to a series of if-else statements.
var age = 20
switch age {
case 0...16: print("You cannot get any type of driving license!")
case 16...18: print("You can get learner's driving license!")
default:
print("You are eligible for permanent driving license!")
}
Loops
To repeat the same statements again and again, we use loops. There are three types of loops provided by Swift.
for loop
// for loop
for counter in 1...10 {
// Check if the counter is divisible by 2
if counter % 2 == 0 {
// Print the counter value if it's divisible by 2
print("\(counter) is divisible by 2")
}
}
Exercise for you: Multiplication Table- Use a for
loop to generate and print the multiplication table for a given number (e.g., 5). Display the results from 1 to 10.
while
In while, you define the variable before the loop and put a condition after using the condition which needs to be true. Then, in the loop we update the variable to stop the loop when condition becomes false.
var counter = 1
while counter < 10 {
// Check if the counter is divisible by 2
if counter % 2 == 0 {
// Print the counter value if it's divisible by 2
print("\(counter) is divisible by 2")
}
// Increment the counter for the next iteration
counter += 1
}
repeat while
The while condition is checked after the first iteration of the loop. This way the loop always gets executed atleast once before condition is checked.
var counter = 1
repeat {
// Check if the counter is divisible by 2
if counter % 2 == 0 {
// Print the counter value if it's divisible by 2
print("\(counter) is divisible by 2")
}
// Increment the counter for the next iteration
counter += 1
} while counter < 10
Functions
Now, what if you want to calculate the simple interest again and again on your code? You can either calculate or simply call a function which sends you the calculated answer.
Once a function is defined, you can call it from different parts of your program, providing a way to reuse the same logic without duplicating the code.
We declare function using func
keyword followed by the function name and in parentheses we have the arguments. Now, arguments are the variables which we are used in the function and are send from the outside.
In the below code simpleInterest
is the name of function, principal, rate, time
are the arguments and ->
tells that our functions returns a value of type Double. A function might or might not return a value.
// returns a Double type value
func simpleInterest(principal:Double, rate:Double, time:Double) -> Double {
return (principal*rate*time)/100
}
let p = 10000.0, r = 10.0, t = 1.0
let SI = simpleInterest(principal:p, rate: r, time: t)
print("SI for p: \(p), r: \(r) and t: \(t) is \(SI)")
// doesn't return anything
func greet(name:String, message:String) {
print("Hi \(name)! \(message)")
}
greet(name:"Ayesha", message:"How are you?")
Functions enable you to break down a complex program into smaller, more manageable parts. Each function can represent a specific task or functionality.
Exercise for you: Write a function called calculateRectangleArea
that takes the length and width as parameters and returns the area.
Conclusion
In this beginner’s introduction to Swift Programming, we covered fundamental concepts such as variables, conditionals, loops, and functions. These form the building blocks of Swift development. Practice writing code to reinforce your understanding, and stay tuned for our upcoming article where we’ll delve into classes and protocols.
Quick Reference
var variableName = value
let constantName = value
if condition {
// Code block
} else if anotherCondition {
// Code block
} else {
// Code block
}
switch variable {
case value1:
// Code block
case value2:
// Code block
default:
// Code block
}
for item in collection {
// Code block
}
while condition {
// Code block
}
repeat {
// Code block
} while condition
func functionName(parameter1: Type, parameter2: Type) -> ReturnType {
// Code block
return value
}