Swift from Scratch: A Complete Guide (Part 1)

Variables and Constants in Swift (var, let)

Variables

// 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

Constants

// 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

Data Types in Swift

Int (Integer)

// Declaring an integer variable
var value: Int = 30
print(value)  // Output: 25

Double

// Declaring a double variable
var price: Double =23.55
print(price)  // Output: 23.55

Float

// Declaring a float variable
var temp: Float = 32.5
print(temp)  // Output: 32.5

String

// Declaring a string variable
var greet: String = "Hello, Inspire The Dev!"
print(greet)  // Output: Hello, Inspire The Dev!

Bool

// Declaring a boolean variable
var swiftIsFun: Bool = true
print(swiftIsFun)  // Output: true

Character

// Declaring a character variable
var keyword: Character = "A"
print(keyword)  // Output: A

Type Inference vs Explicit Type Declaration

Type Inference

var number = 25  // Type inferred as Int

Explicit Type Inference

var name: String = "Inspire"

Control Flow in Swift

Conditional Statements: If-Else

If Statement

let marks = 90

if marks >= 90 {
    print("you were selected")  // Output: you were selected
}

If-Else Statement

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

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

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

let fruit = "Apple"

switch fruit {
case "Apple", "Banana":
    print("Popular fruit")  // Output: Popular fruit
default:
    print("WaterMelon")
}

Range Matching in Switch

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

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

for i in 1...5 {
    print(i)  // Output: 1 2 3 4 5
}

While Loop

var counter = 0

while counter < 5 {
    print(counter)  // Output: 0 1 2 3 4
    counter += 1
}

Repeat-while Loop

var counter = 0

repeat {
    print(counter)  // Output: 0 1 2 3 4
    counter += 1
} while counter < 5

Function

func functionName(parameters) -> returnType {
    // Function body (code to be executed)
}

Function Without Parameters and Return Value

func greet() {
    print("Hello, welcome to Swift programming!")
}

greet()  // Output: Hello, welcome to Swift programming!

Function with Parameters

func greetUser(name: String) {
    print("Hello, \(name)! Welcome to Swift programming!")
}

greetUser(name: "Raj")  // Output: Hello, Raj! Welcome to Swift programming!

Function with Return Value

func addNumbers(a: Int, b: Int) -> Int {
    return a + b
}

let sum = addNumbers(a: 10, b: 20)
print(sum)  // Output: 30

Function with Multiple Parameters

func calculateArea(length: Int, width: Int) -> Int {
    return length * width
}

let area = calculateArea(length: 5, width: 10)
print(area)  // Output: 50

Function Overloading

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!

Optional

var number: Int?
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)

Why Use Optionals?

Optional Binding

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")
}

Forced Unwrapping

var age: Int? = 25
print(age!)  // Output: 25

Nil Coalescing Operator

let value = optionalValue ?? defaultValue
// code 
let number: Int?
let value = number ?? 30
print(value) // output 30

Conclusion

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *