Blog

  • PHP Tutorials: Complete Learning Roadmap

    This page provides a structured roadmap to learning PHP, from core syntax and control structures to advanced topics, object-oriented programming, and database integration.


    Overview of PHP Tutorials

    A comprehensive guide covering PHP fundamentals, advanced concepts, and real-world application development.


    Introduction to PHP

    Learn the basics of PHP, its purpose, and how it is used in web development.

    • Introduction to Java (move or remove if unrelated — this should not be on a PHP page)
    • Characteristics of PHP
    • Basic Concepts of PHP

    PHP Syntax and Language Fundamentals

    Understand how PHP code is written and executed.

    • PHP Basic Syntax
    • Writing Comments in PHP
    • PHP Variables
    • PHP echo and print
    • PHP Data Types
    • PHP Strings

    Working with Arrays in PHP

    Learn how PHP handles collections of data.

    • Introduction to PHP Arrays
    • Indexed Arrays in PHP
    • Associative Arrays in PHP
    • Multidimensional Arrays in PHP
    • Sorting Arrays in PHP

    PHP Constants Explained

    Define and use constants effectively in PHP.

    • PHP Constants Overview
    • Defining Constants in PHP
    • PHP Magic Constants

    PHP Operators and Expressions

    Understand how PHP performs calculations and logical operations.

    • Overview of PHP Operators
    • Arithmetic and Logical Operators
    • Bitwise Operators in PHP
    • Ternary Operator in PHP

    Control Flow and Decision Making in PHP

    Control the execution flow of your PHP programs.

    • PHP Conditional Statements
    • PHP switch Statement
    • PHP break Statement (Single and Nested Loops)
    • PHP continue Statement

    Looping Constructs in PHP

    Repeat operations efficiently using loops.

    • Overview of PHP Loops
    • while Loop in PHP
    • do-while Loop in PHP
    • for Loop in PHP
    • foreach Loop in PHP

    PHP Functions and Reusability

    Write reusable blocks of code using functions.

    • Introduction to PHP Functions
    • PHP Arrow Functions
    • Anonymous and Recursive Functions in PHP

    Advanced PHP Concepts

    Explore advanced features used in real-world applications.

    • PHP Superglobals
    • HTTP GET and POST Methods
    • Regular Expressions in PHP
    • PHP Form Processing
    • Date and Time Functions
    • Include and Require Statements
    • Basics of File Handling
    • File Uploading in PHP
    • Cookies in PHP
    • Sessions in PHP
    • Callback Functions in PHP

    Object-Oriented Programming in PHP

    Master OOP principles using PHP.

    • Introduction to PHP OOP
    • PHP Classes and Objects
    • Constructors and Destructors
    • Access Specifiers in PHP
    • Multiple Inheritance Concepts in PHP
    • Class Constants in PHP
    • Abstract Classes in PHP
    • Interfaces in PHP
    • Static Methods in PHP
    • PHP Namespaces

    PHP and MySQL Database Integration

    Learn how PHP works with MySQL databases.

    • Introduction to MySQL with PHP
    • Database Connections in PHP
    • Connecting PHP to MySQL
    • Creating Tables in MySQL
    • Inserting Data into MySQL
    • Selecting Data Using MySQL Queries
    • Deleting Records in MySQL
    • Using WHERE Clause in MySQL
    • Updating Records in MySQL
    • LIMIT Clause in MySQL

    PHP Built-in Functions Reference

    A complete reference to commonly used PHP functions.

    Array and String Functions

    • PHP Array Functions Reference
    • PHP String Functions Reference
    • PHP Math Functions Reference

    File and System Functions

    • PHP Filesystem Functions Reference
    • PHP DOM Functions Reference

    Internationalization Functions

    • PHP Intl Functions Reference
    • PHP IntlChar Functions Reference

    Image Processing Libraries

    • PHP GD Image Functions
    • PHP Imagick Functions
    • PHP ImagickDraw Functions
    • PHP Gmagick Functions

    Data Structures Extensions

    • PHP GMP Functions
    • PHP SPL Data Structures
    • PHP Ds\Vector Functions
    • PHP Ds\Set Functions
    • PHP Ds\Map Functions
    • PHP Ds\Stack Functions
    • PHP Ds\Queue Functions
    • PHP Ds\Deque Functions
    • PHP Ds\Sequence Functions

    Final Notes

    This PHP roadmap is designed to help learners progress logically from fundamentals to advanced topics. Each section builds on the previous one, ensuring clarity, consistency, and scalability for both learners and search engines.

  • Swift Project Ideas

    Below are 10 solid Swift/iOS project ideas with clear descriptions, feature lists, and suggested tech stacks. These range from beginner-friendly to advanced (AR, ML, realtime, multiplayer).


    1) Task & Habit Tracker App

    Description:
    A productivity app to manage tasks and build habits with streak tracking and gamification.

    Key Features

    • Create, edit, delete tasks
    • Reminders + recurring habits
    • Streak tracking with charts
    • Gamification: points, badges, levels
    • iCloud sync across devices

    Suggested Tech Stack

    • UI: SwiftUI
    • Storage: Core Data
    • Sync: CloudKit
    • Notifications: UserNotifications

    2) Recipe Finder with AR Integration

    Description:
    Users enter (or scan) ingredients and get recipe suggestions; AR overlays step-by-step cooking instructions.

    Key Features

    • Ingredient input + optional scanning
    • Dietary filters (vegan, keto, allergies)
    • Save favorites + sharing
    • AR step overlay (timers, steps, visuals)

    Suggested Tech Stack

    • UI: SwiftUI or UIKit
    • Ingredient recognition: Vision + Core ML
    • AR: ARKit
    • Recipe data: Spoonacular API (or similar)

    3) Personal Finance Tracker

    Description:
    Track income/expenses, budget monthly, and visualize spending patterns.

    Key Features

    • Expense categories + custom tags
    • Monthly summaries and analytics
    • Charts (pie/bar/line)
    • Savings goals + progress tracking
    • Export as CSV/PDF
    • Secure with Face ID / Touch ID

    Suggested Tech Stack

    • Storage: Core Data or SQLite
    • Charts: Swift Charts (iOS 16+) or a charts library
    • Security: LocalAuthentication
    • Export: PDFKit / file generation

    4) Real-Time Chat Application

    Description:
    A chat app supporting 1:1 and group chats with media sharing.

    Key Features

    • Text + image/video messages
    • Group chats + typing indicators
    • Read receipts
    • Push notifications
    • Optional: end-to-end encryption

    Suggested Tech Stack

    • Backend: Firebase (Firestore/Realtime DB)
    • Auth: Firebase Authentication
    • Push: Firebase Cloud Messaging (FCM)
    • UI: UIKit (custom chat UI) or SwiftUI with custom views

    5) Fitness App with Workout Tracking

    Description:
    Track workouts, goals, and health metrics with optional Apple Watch support.

    Key Features

    • Workout plans (predefined + custom)
    • Health metrics via HealthKit
    • Real-time stats (heart rate/calories) with Apple Watch
    • Goal setting and history tracking
    • Social sharing / comparison

    Suggested Tech Stack

    • Health data: HealthKit
    • Watch app: WatchKit
    • UI: SwiftUI
    • Storage: Core Data (optional)

    6) News Aggregator App

    Description:
    Aggregates news from multiple sources, supports custom feeds and offline reading.

    Key Features

    • Fetch news from APIs (category/source filters)
    • Save articles for offline reading
    • Dark mode + dynamic themes
    • Push notifications for breaking news

    Suggested Tech Stack

    • Networking: URLSession + Combine
    • Storage: Core Data
    • UI: SwiftUI
    • Push: APNs or Firebase Messaging

    7) Multiplayer Game with SpriteKit

    Description:
    A 2D real-time multiplayer game with physics interactions.

    Key Features

    • Local multiplayer (same network)
    • Online multiplayer matchmaking
    • Physics-based gameplay
    • Game Center leaderboards/achievements
    • In-app purchases (skins, boosters)

    Suggested Tech Stack

    • Game engine: SpriteKit
    • Local multiplayer: Multipeer Connectivity
    • Online multiplayer backend: Firebase or custom server
    • Leaderboards: Game Center
    • Purchases: StoreKit

    8) E-Commerce Store App

    Description:
    A complete shopping experience for a niche store or small business.

    Key Features

    • Product browsing + search
    • Filters/sorting + product detail pages
    • Cart + checkout
    • Payments (Stripe/PayPal)
    • Order tracking + notifications
    • Admin panel (optional)

    Suggested Tech Stack

    • Frontend: SwiftUI
    • Backend: Vapor (Swift server-side)
    • Database: PostgreSQL
    • Payments: Stripe SDK / PayPal SDK
    • Push notifications: APNs

    9) Custom Photo Editor

    Description:
    A photo editor with filters, cropping, annotation tools, and AI-based background removal.

    Key Features

    • Filters and adjustments (brightness/contrast)
    • Crop/rotate
    • Draw/annotate + stickers
    • Background removal via ML
    • Undo/redo stack
    • Export in multiple formats

    Suggested Tech Stack

    • Image processing: Core Image
    • ML: Vision + Core ML
    • UI: UIKit (often easier for editors) or SwiftUI
    • Export: Photos framework / file export APIs

    10) Language Learning App

    Description:
    A gamified language-learning app using spaced repetition and daily practice loops.

    Key Features

    • Flashcards + spaced repetition scheduling
    • Text-to-speech pronunciation
    • Daily challenges + streaks
    • Leaderboards and achievements
    • Offline mode

    Suggested Tech Stack

    • Text-to-speech: AVSpeechSynthesizer
    • Storage: Core Data or Realm
    • Gamification: Game Center
    • UI: SwiftUI

    Quick Picks (If You’re Choosing One)

    • Beginner-friendly: Task & Habit Tracker, News Aggregator
    • Intermediate: Finance Tracker, Photo Editor
    • Advanced: AR Recipe Finder, Real-time Chat, Multiplayer SpriteKit game, E-commerce + Vapor backend

  • Swift Interview Questions and Answers

    Theoretical Questions

    1. What is the difference between a class and a structure in Swift?

    Answer:

    • Class: Reference type, supports inheritance, uses reference counting, mutable properties by default.
    • Structure: Value type, no inheritance, copied on assignment, properties are immutable unless declared with var.

    2. Explain the purpose of guard in Swift.

    Answer:
    guard is used for early exit from a function or loop when a condition is not met. It enhances code readability by avoiding nested code.

    func checkAge(_ age: Int?) {
        guard let age = age, age >= 18 else {
            print("You must be at least 18 years old.")
            return
        }
        print("You are eligible.")
    }

    3. What is the difference between mapflatMap, and compactMap?

    Answer:

    • map: Transforms each element and returns an array of optional values.
    • flatMap: Flattens nested collections or removes nil values when used on optionals.
    • compactMap: Returns a new array with non-nil values after transformation.

    4. What are protocol extensions, and how are they useful?

    Answer:
    Protocol extensions allow you to provide default implementations of methods or properties in protocols, enabling code reuse and avoiding duplicate code across conforming types.

    5. Explain what defer does in Swift.

    Answer:
    defer executes a block of code just before the current scope exits, ensuring cleanup or finalization.

    func readFile() {
        let file = openFile("example.txt")
        defer {
            closeFile(file)
        }
        // File operations
    }

    Advanced Coding Challenges

    6. Write a function to check if a string is a palindrome.

    Answer:

    func isPalindrome(_ str: String) -> Bool {
        let cleaned = str.lowercased().filter { $0.isLetter }
        return cleaned == String(cleaned.reversed())
    }
    print(isPalindrome("A man, a plan, a canal, Panama")) // true

    7. Implement a function to remove duplicates from an array.

    Answer:

    func removeDuplicates<T: Hashable>(_ array: [T]) -> [T] {
        var seen = Set<T>()
        return array.filter { seen.insert($0).inserted }
    }
    print(removeDuplicates([1, 2, 2, 3, 4, 4])) // [1, 2, 3, 4]

    8. Write a generic function to find the maximum element in an array.

    Answer:

    func findMax<T: Comparable>(_ array: [T]) -> T? {
        return array.max()
    }
    print(findMax([3, 1, 4, 1, 5, 9])) // 9

    9. How would you implement a singleton in Swift?

    Answer:

    class Singleton {
        static let shared = Singleton()
        private init() {}
    }
    let instance = Singleton.shared

    10. Write a function to calculate the factorial of a number recursively.

    Answer:

    func factorial(_ n: Int) -> Int {
        return n <= 1 ? 1 : n * factorial(n - 1)
    }
    print(factorial(5)) // 120

    Advanced Questions

    11. What is the difference between weak, strong, and unowned references?

    Answer:

    • Strong: Default, increments the reference count.
    • Weak: Does not increment the reference count, allows the reference to become nil.
    • Unowned: Does not increment the reference count, assumes the reference will never be nil.

    12. Explain Swift’s type inference. When should you explicitly specify types?

    Answer:

    • Type inference automatically determines the type based on the assigned value.
    • Explicit types are useful for clarity or when the value may change in the future.

    13. Explain how Combine framework handles asynchronous events and its advantages over traditional patterns like delegation or completion handlers.

    Answer:

    • Combine uses publishers and subscribers for reactive programming, enabling chaining and transformation of data streams. It reduces boilerplate and provides a declarative API.
    • Example:
    import Combine
    
    let publisher = Just("Hello, Combine!")
    let subscription = publisher.sink { print($0) }

    14. How do you handle asynchronous code in Swift?

    • Answer:
      Using GCD, async/await, or operation queues. Example with async/await:
    func fetchData() async throws -> String {
        return try await URLSession.shared.data(from: URL(string: "https://example.com")!).0.description
    }

    15. What are property wrappers, and how are they used?

    Answer:
    Property wrappers add behavior to properties. Example:

    @propertyWrapper
    struct Capitalized {
        private var value: String = ""
        var wrappedValue: String {
            get { value }
            set { value = newValue.capitalized }
        }
    }
    struct User {
        @Capitalized var name: String
    }
    var user = User()
    user.name = "john"
    print(user.name) // John

    Scenario-Based Questions

    16. How would you debug retain cycles in a Swift project?

    Answer:
    Use Xcode’s memory graph debugger or analyze references to detect strong reference cycles. Resolve cycles using weak or unowned.

    17. Write a function that reverses an array in place.

    Answer:

    func reverseArray<T>(_ array: inout [T]) {
        array.reverse()
    }
    var nums = [1, 2, 3, 4, 5]
    reverseArray(&nums)
    print(nums) // [5, 4, 3, 2, 1]

    18. What is a Result type, and how is it used in Swift?

    Answer:

    • Result encapsulates success and failure cases.
    enum MyError: Error { case example }
    func divide(_ a: Int, by b: Int) -> Result<Int, MyError> {
        b == 0 ? .failure(.example) : .success(a / b)
    }
    let result = divide(10, by: 0)
    switch result {
    case .success(let quotient): print("Quotient: \(quotient)")
    case .failure(let error): print("Error: \(error)")
    }

    19. How do you implement dependency injection in Swift?

    Answer:

    • Use initializer or property injection
    protocol Service {
        func fetchData()
    }
    class APIService: Service {
        func fetchData() { print("Fetching data...") }
    }
    class Controller {
        private let service: Service
        init(service: Service) { self.service = service }
        func loadData() { service.fetchData() }
    }
    let controller = Controller(service: APIService())
    controller.loadData()

    20. What are the differences between @escaping and @nonescaping closures? In what scenarios would you use each?

    Answer:

    • @escaping: The closure is stored and executed after the function scope has ended. Used in asynchronous operations like network requests.
    • @nonescaping: The closure is executed within the function’s scope. Used for immediate, synchronous tasks.
  • Swift Additional Topics

    Swift Errors

    Error handling refers to the process of responding to issues that arise during the execution of a function. A function can raise an error when it encounters an exceptional condition. The error can then be caught and addressed appropriately. Essentially, error handling allows us to deal with errors gracefully without abruptly exiting the code or application.

    In this explanation, we’ll focus on what happens when an error is raised versus when it is not. Below is an example of a function, canThrowAnError(), demonstrating error handling implemented outside the loop in Swift.

    Example 1:

    func canThrowAnError() throws {
        // This function may or may not throw an error
    }
    
    do {
        try canThrowAnError()
        // No error was thrown
    }
    catch {
        // An error was thrown
    }
    Real-world Scenario

    Case 1: The function throws an error.

    For example, the function startCar() will raise an error if the seatbelt is not fastened or the fuel is low. Since startCar() can throw an error, it is wrapped in a try expression. When such a function is used within a do block, any errors it throws can be caught and handled using the appropriate catch clauses.

    Case 2: The function does not throw an error.

    If no error is raised when the function is called, the program continues executing without interruption. However, if an error occurs, it will be matched to a specific catch clause. For instance:

    • If the error corresponds to the carError.noSeatBelt case, the blinkSeatBeltSign() function will be called.
    • If the error matches the carError.lowFuel case, the goToFuelStation(_:) function will be invoked, using the associated fuel-related details provided by the catch pattern.

    Example:

    func startCar() throws {
        // Logic to start the car, which may throw an error
    }
    
    do {
        try startCar()
        turnOnAC()
    }
    catch carError.noSeatBelt {
        blinkSeatBeltSign()
    }
    catch carError.lowFuel(let fuel) {
        goToFuelStation(fuel)
    }

    Output:

    1. If no error is thrown:

    • The car starts, and the air conditioner is turned on.

    2. If an error is thrown:

    • For carError.noSeatBelt, the seatbelt sign blinks.
    • For carError.lowFuel, the function goToFuelStation(_:) is executed with the relevant fuel information.

    Difference between Try, Try?, and Try! in Swift

    Exception Handling in Swift

    In any programming language, exception handling is essential for maintaining code reliability and stability. With Swift’s rise as a robust and versatile language, developers encounter new methods and opportunities for managing errors and unexpected scenarios. This article provides an overview of how Swift handles exceptions effectively.

    Similar to other languages, Swift includes keywords to address undefined behaviors or exceptions in a program. Swift provides three distinct ways to manage errors using the keywords trytry?, and try!.

    Example:

    import Swift
    
    func foo() throws -> Int? {
        print("I am inside foo()")
        throw SomeError // Part of the code that will throw an exception
    }
    Try

    The first approach for handling exceptions in Swift is using the try keyword within a do block. This method is comparable to try-catch blocks in other languages like Java. The code that might throw an error is enclosed in a do block with try preceding the function call. If an error is thrown, it is caught by the accompanying catch block.

    Example:

    do {
        let x = try foo()
        print("This will be printed if there isn't any error.")
    } catch {
        print("Caught an error while calling function foo()!")
    }

    Output:

    • If no error is thrown: This will be printed if there isn’t any error.
    • If an error is thrown: Caught an error while calling function foo()!
    Try?

    The second method involves using try?. When used, try? transforms errors into optional values. If an error occurs, the value becomes nil, allowing the program to continue execution without disruption.

    Example 1:

    let x = try? foo()
    
    if let safex = x {
        print("x has a value which is \(safex)")
    } else {
        print("x has a nil value")
    }
    Try!

    The third method, try!, is used when the programmer is confident that the function will not throw an error. If an error occurs, the program will halt execution. The exclamation mark (!) indicates a forceful approach, bypassing error handling and focusing solely on program flow.

    Example:

    let x = try! foo()
    print("Execution will never reach here! Program halts above this line.")

    Output:

    • If no error is thrown: [Execution proceeds normally]
    • If an error is thrown: Program terminates immediately.

    Swift Typealias

    A variable is a named container used to store a value. Each value has a type, known as a data type, which is a classification of data that tells the compiler how the data is intended to be used. Data types can be categorized as primitive, user-defined, and derived. Swift provides specific data types like Int for integers, Float or Double for decimal values, and String for text. Many programming languages offer a way to refer to data types with alternate names or aliases. In Swift, the keyword typealias is used for this purpose.

    Type Alias in Swift

    Swift allows creating aliases for existing data types, offering a new name to refer to a data type without creating a new type. The typealias keyword serves this purpose and is similar to the typedef keyword in C++. Multiple aliases can be defined for a single data type.

    Syntax:

    typealias myDataType = dataType

    Here:

    • typealias is the keyword.
    • dataType refers to a primitive, user-defined, or complex data type.
    • myDataType is the alias, which can now be used interchangeably with dataType.

    1. Type Alias for Primitive Data Types: Swift allows aliases for primitive data types like IntFloat, and Double. Internally, typealias does not create new data types but provides alternate names for existing ones.

    Syntax:

    typealias myDataType = dataType

    Example:

    // Swift program demonstrating typealias for primitive data types
    
    // Defining aliases
    
    typealias myInt = Int
    typealias myFloat = Float
    typealias myDouble = Double
    typealias myCharacter = Character
    typealias myString = String
    
    // Using aliases
    var integerNumber: myInt = 5
    print("integerNumber:", integerNumber)
    
    var floatNumber: myFloat = 5.12345
    print("floatNumber:", floatNumber)
    
    var doubleNumber: myDouble = 5.123456789
    print("doubleNumber:", doubleNumber)
    
    var character: myCharacter = "A"
    print("character:", character)
    
    var string: myString = "Hello, Swift!"
    print("string:", string)

    Output:

    integerNumber: 5
    floatNumber: 5.12345
    doubleNumber: 5.123456789
    character: A
    string: Hello, Swift!

    2. Type Alias for User-Defined Data Types: User-defined data types like structures, arrays, and classes can also be assigned aliases. This is particularly useful for simplifying complex types.

    Syntax:

    typealias myDataType = dataType

    Example:

    // Swift program demonstrating typealias for user-defined data types
    
    struct Employee {
        var employeeName: String
        var employeeId: Int
    
        init(employeeName: String, employeeId: Int) {
            self.employeeName = employeeName
            self.employeeId = employeeId
        }
    }
    
    typealias employees = Array<Employee>
    
    // Creating an array of Employee objects
    var myArray: employees = []
    
    // Adding Employee objects
    myArray.append(Employee(employeeName: "Alice", employeeId: 101))
    myArray.append(Employee(employeeName: "Bob", employeeId: 102))
    myArray.append(Employee(employeeName: "Charlie", employeeId: 103))
    
    // Printing array elements
    for element in myArray {
        print("Employee Name:", element.employeeName, ", Employee ID:", element.employeeId)
    }

    Output:

    Employee Name: Alice , Employee ID: 101
    Employee Name: Bob , Employee ID: 102
    Employee Name: Charlie , Employee ID: 103

    3. Type Alias for Complex Data Types: Complex data types consist of multiple primitive types or involve functions. Swift allows defining aliases for such types as well.

    Syntax:

    // Swift program demonstrating typealias for complex types
    
    typealias functionType = (Int, Int) -> Int
    
    // Function for multiplication
    func multiply(a: Int, b: Int) -> Int {
        return a * b
    }
    
    // Using the alias for function type
    var myFunction: functionType = multiply
    
    let number1 = 7
    let number2 = 8
    let result = myFunction(number1, number2)
    
    print("Multiplication of", number1, "and", number2, "is", result)
    Output:
    Multiplication of 7 and 8 is 56

    Difference between Swift Structures and C Structure

    Swift Structures

    Swift structures are a fundamental feature of the Swift programming language. They enable the grouping of related data into a single unit. While similar to classes, structures have notable differences:

    • Value Types: Structures in Swift are value types, which means assigning or passing them creates a copy, ensuring the original structure remains unchanged. This behavior can lead to improved performance and avoids unintended modifications.
    • Memberwise Initializers: Swift automatically provides memberwise initializers, simplifying the initialization of structure properties.
    • No Inheritance: Structures cannot inherit properties or behavior from other structures or classes, making them more lightweight and focused.
    • Methods and Properties: Swift structures can define both methods and properties, enabling encapsulation of data and behavior.
    • Performance: Structures can be faster than classes because they avoid dynamic dispatch and reference counting overhead.

    Example:

    // Defining a structure
    struct Car {
        var make: String
        var model: String
        var year: Int
    }
    
    // Creating a structure instance
    var car = Car(make: "Toyota", model: "Camry", year: 2020)
    
    print("\(car.make) \(car.model) was manufactured in \(car.year).")
    
    // Modifying a property
    car.year = 2022
    
    print("\(car.make) \(car.model) is now updated to year \(car.year).")

    Output:

    Toyota Camry was manufactured in 2020.
    Toyota Camry is now updated to year 2022.
    Structures

    In C, structures are composite data types used to group variables of different types under one name. Each variable within the structure is called a member. Structures are commonly used for organizing related data, simplifying management and readability in programs.

    Example:

    #include <stdio.h>
    #include <string.h>
    
    // Defining a structure
    struct Book {
        char title[50];
        char author[50];
        int year;
    };
    
    int main() {
        // Creating a structure instance
        struct Book book;
    
        // Initializing members
        strcpy(book.title, "The C Programming Language");
        strcpy(book.author, "Brian W. Kernighan and Dennis M. Ritchie");
        book.year = 1978;
    
        // Displaying structure data
        printf("Title: %s\nAuthor: %s\nYear: %d\n", book.title, book.author, book.year);
    
        return 0;
    }

    Output:

    Title: The C Programming Language
    Author: Brian W. Kernighan and Dennis M. Ritchie
    Year: 1978

    Differences Between Swift Structures and C Structures

    FeatureSwift StructuresC Structures
    InheritanceNot supported.Not supported.
    Methods and PropertiesSupport both methods and properties.Only contain members (data fields).
    InitializationProvide automatic memberwise initializers and allow custom initializers.Require manual initialization for each member.
    Pass by ValueAlways passed by value.Can be passed by value or by reference.
    Type SafetyStrong typing ensures type safety.Relatively loose typing.
    Memory ManagementManaged automatically with ARC (Automatic Reference Counting).Requires manual memory management.
    MutabilityProperties are immutable unless declared as var.Members are mutable by default.
    Named vs AnonymousStructures must have a name.Can be anonymous and embedded within other structures.
    Type AliasingCan be type-aliased for better code readability.Type aliasing is not directly supported.
  • Swift OOPs: Object-Oriented Programming in Swift

    Swift supports object-oriented programming through classes, and it also provides powerful value-type alternatives such as structures and enumerations. Understanding how types, properties, methods, initialization, and memory management work is essential for writing clean and scalable Swift code.


    Structures in Swift

    A struct groups related data and behavior into a single type. Structures are value types, meaning they are copied when assigned or passed into functions.

    Structure Syntax

    struct StructureName {
        // properties and methods
    }
    

    Example: Defining and Creating a Struct

    struct Employee {
        var name: String
        var id: Int
        var department: String
        var joiningYear: Int
    }
    
    let employee = Employee(name: "Mohit", id: 1234, department: "HR", joiningYear: 2019)
    print(employee.name)
    print(employee.joiningYear)
    

    Memberwise Initializers in Structs

    Swift automatically generates a memberwise initializer for structs.

    struct Employee {
        var name: String
        var id: Int
    }
    
    let updated = Employee(name: "Mohit", id: 5678)
    print(updated.id)
    

    Methods in Structures

    Structs can contain methods (functions inside types).

    struct Salary {
        var baseSalary: Int
    
        func calculateIncrement() {
            let newSalary = 2 * baseSalary
            print("New Salary: \(newSalary)")
        }
    }
    
    let salary = Salary(baseSalary: 230000)
    salary.calculateIncrement()
    

    Using self in Swift

    self refers to the current instance. It’s especially useful when parameter names match property names.

    struct Article {
        var count = 230
    
        func update(count: Int = 23) {
            print("Parameter count: \(count)")
            print("Stored count: \(self.count)")
        }
    }
    
    Article().update()
    

    Properties in Swift

    Properties store or compute values inside a type. The most common types are:

    • Stored properties (saved in memory)
    • Computed properties (calculated via getters/setters)
    • Lazy properties (initialized only when first used)
    • Property observers (run when values change)

    Stored Properties

    struct Person {
        var name: String
    }
    
    let person = Person(name: "John")
    print(person.name)
    

    Lazy Stored Properties

    Lazy properties are useful when initialization is expensive.

    class Course {
        var courseName: String
    
        lazy var description: String = {
            "Course: \(courseName)"
        }()
    
        init(courseName: String) {
            self.courseName = courseName
        }
    }
    
    let course = Course(courseName: "Swift")
    print(course.description)
    

    Computed Properties

    Computed properties calculate a value instead of storing it.

    struct Rectangle {
        var length: Double
        var width: Double
    
        var perimeter: Double {
            get { 2 * (length + width) }
            set { length = (newValue / 2) - width }
        }
    }
    
    var rect = Rectangle(length: 10, width: 5)
    print(rect.perimeter)
    rect.perimeter = 40
    print(rect.length)
    

    Read-Only Computed Properties

    struct Cuboid {
        var width: Double
        var height: Double
        var depth: Double
    
        var volume: Double {
            width * height * depth
        }
    }
    
    let box = Cuboid(width: 4, height: 4, depth: 4)
    print(box.volume)
    

    Property Observers (willSet, didSet)

    class StepCounter {
        var totalSteps: Int = 0 {
            willSet { print("About to set total steps to \(newValue)") }
            didSet {
                if totalSteps > oldValue {
                    print("Added \(totalSteps - oldValue) steps")
                }
            }
        }
    }
    
    let counter = StepCounter()
    counter.totalSteps = 105
    counter.totalSteps = 240
    

    Methods in Swift

    Methods are functions associated with a type. Swift supports:

    • Instance methods (called on objects)
    • Type methods (called on the type itself)

    Instance Methods Example

    class Calculator {
        let result: Int
    
        init(x: Int, y: Int) {
            self.result = x + y
        }
    
        func subtract(by value: Int) -> Int {
            result - value
        }
    }
    
    let calculator = Calculator(x: 200, y: 300)
    print(calculator.subtract(by: 50))
    

    External and Local Parameter Names

    class Divider {
        func divide(_ numerator: Int, by denominator: Int) {
            print("Quotient is: \(numerator / denominator)")
        }
    }
    
    Divider().divide(120, by: 3)
    

    Mutating Methods in Value Types

    Structs need mutating methods to modify stored properties.

    struct Rectangle {
        var length: Int
        var width: Int
    
        mutating func scale(by factor: Int) {
            length *= factor
            width *= factor
            print("Length=\(length), Width=\(width)")
        }
    }
    
    var r = Rectangle(length: 4, width: 5)
    r.scale(by: 2)
    

    Type Methods (static and class)

    class MathOperations {
        class func absoluteValue(of number: Int) -> Int {
            number < 0 ? -number : number
        }
    }
    
    struct Utility {
        static func absoluteValue(of number: Int) -> Int {
            number < 0 ? -number : number
        }
    }
    
    print(MathOperations.absoluteValue(of: -10))
    print(Utility.absoluteValue(of: -20))
    

    Function vs Method in Swift

    • A function is standalone (global or local scope)
    • A method belongs to a type (class/struct/enum)

    Function Example

    func greet() {
        print("Hello Swift!")
    }
    
    greet()
    

    Method Example

    struct Developer {
        let speed: Int
        func learn() { print("Learning at \(speed) MPH") }
        static func code() { print("Writing Swift code") }
    }
    
    Developer(speed: 15).learn()
    Developer.code()
    

    Deinitialization in Swift (deinit)

    Only classes support deinitializers because classes use ARC (Automatic Reference Counting).

    var x = 10
    
    class DeinitializerExample {
        init() { x += 10 }
        deinit { x = 0 }
    }
    
    var obj: DeinitializerExample? = DeinitializerExample()
    print("Before deinit: \(x)")
    obj = nil
    print("After deinit: \(x)")
    

    Typecasting in Swift

    Typecasting helps you check or convert types at runtime.

    Upcasting (Safe)

    class Animal { func sound() { print("Animal sound") } }
    class Dog: Animal { override func sound() { print("Woof") } }
    
    let dog = Dog()
    let animal: Animal = dog
    animal.sound()
    

    Type Checking with is

    let value: Any = 42
    if value is Int {
        print("value is an Int")
    }
    

    Downcasting with as? and as!

    class Vehicle { }
    class Car: Vehicle { var brand = "Tesla" }
    
    let v: Vehicle = Car()
    if let c = v as? Car {
        print(c.brand)
    }
    

    Summary

    Swift supports OOP through classes and complements it with powerful value types like structs. Key topics covered:

    • Structs (value types) and how they work
    • Stored, computed, lazy properties and observers
    • Instance methods, type methods, and mutating
    • Functions vs methods
    • ARC and deinit
    • Typecasting with is, as?, and as!

  • Swift Tuples

    A tuple in Swift is a constant or variable that can hold a group of values, which can be of different data types, combined into a single value. In simpler terms, a tuple is a structure that allows multiple values of various types to be stored together. Tuples are often used as return values to retrieve multiple data points from a function or process.

    Creating a Tuple in Swift

    To create a tuple, declare a constant or variable and define the data inside parentheses () separated by commas. The elements can be of the same or distinct data types.

    Example 1: Declaring a Tuple Containing a String and an Integer

    // statusLoad is of type (String, Int) and equals (“Forbidden”, 403)
    let statusLoad = ("Forbidden", 403)

    Here, the tuple statusLoad holds two values:

    • String providing a human-readable description ("Forbidden")
    • An Int representing a numeric code (403)

    Example 2: Declaring Tuples with Multiple Data Types

    let a = (1, 2, 3, 4)
    var b = ("Hello", 42, "Swift", 7, 99)

    Tuples can also have named elements for better readability.

    Example 3: Naming Elements Inside a Tuple

    let statusLoad = (tupleMessage: "Forbidden", tupleCode: 403)
    Decomposing a Tuple

    You can access tuple elements by decomposing the tuple into variables or constants, as shown below:

    // Refer to statusLoad from above
    let (sMessage, sCode) = statusLoad
    
    // Print the message
    print("The status message is \(sMessage).")
    
    // Print the code
    print("The status code is \(sCode).")

    Output:

    The status message is Forbidden.
    The status code is 403.

    Example 4: Accessing Tuple Elements Using Indexes

    You can access elements in a tuple using their index.

    let person = ("John", 25, "Developer")
    
    // Accessing elements by index
    print("Name: \(person.0)")
    print("Age: \(person.1)")
    print("Profession: \(person.2)")

    Output:

    Name: John
    Age: 25
    Profession: Developer

    Example 5: Naming Tuple Elements and Accessing Them

    Named elements make accessing tuple values more intuitive.

    let book = (title: "Swift Programming", author: "John Doe", pages: 350)
    
    // Accessing elements by name
    print("Book Title: \(book.title)")
    print("Author: \(book.author)")
    print("Number of Pages: \(book.pages)")

    Output:

    Book Title: Swift Programming
    Author: John Doe
    Number of Pages: 350

    Example 6: Returning a Tuple from a Function

    Tuples are commonly used as return types for functions when you want to return multiple values.

    func getDeviceInfo() -> (name: String, price: Double, inStock: Bool) {
        return ("iPhone", 999.99, true)
    }
    
    let device = getDeviceInfo()
    
    print("Device Name: \(device.name)")
    print("Price: \(device.price)")
    print("In Stock: \(device.inStock)")

    Output:

    myArray: ["Swift", "iOS", "Xcode", "iPad"]

    Example 7: Using a Tuple in a For Loop

    You can use tuples to iterate over key-value pairs in a collection.

    let scores = [("Alice", 90), ("Bob", 85), ("Charlie", 95)]
    
    for (name, score) in scores {
        print("\(name) scored \(score) marks.")
    }

    Output:

    Alice scored 90 marks.
    Bob scored 85 marks.
    Charlie scored 95 marks.

  • Swift Dictionary

    Swift is a programming language designed to work with Apple’s Cocoa and Cocoa Touch frameworks. It is intended to be a modern, safe, and flexible alternative to Objective-C. Swift is actively developed by the open-source community. It offers a collection called dictionaries, which consists of key-value pairs.

    A dictionary is an unordered collection where a key maps to a value. A key can be of any type, such as a string or integer, while the value associated with that key can also be any type of data.

    Creating a Dictionary

    In Swift, a dictionary is created by associating key-value pairs. The key should always be a single item, while the value can be a single item or even a collection such as an array or another dictionary.

    Syntax:

    var someDictionary = [keyType: valueType](key: value)

    Here, keyType and valueType define the types of keys and values, and they are separated by a colon.

    Example:

    // Swift program to create a dictionary
    var someDictionary: [String: String] = ["fruit": "Apple", "vegetable": "Carrot"]
    
    // Displaying key-value pair
    print(someDictionary)

    Output:

    ["vegetable": "Carrot", "fruit": "Apple"]

    Creating an Empty Dictionary

    An empty dictionary contains no key-value pairs. It can be used for storing data as key-value pairs.

    Syntax:

    var emptyDictionary = [keyType: valueType][:]

    Example:

    // Creating an empty dictionary
    var emptyDictionary = [String: String][:]
    print(emptyDictionary) // Output: [:]

    Changing the Value in a Dictionary

    In Swift, the values of a dictionary can be updated using square brackets []. If the key is not found, a new key-value pair is added.

    Syntax:

    Dictionary_name[key] = value

    Example:

    // Swift program to change the value of dictionary
    var someDictionary = ["one": "Mohit", "two": "Rohit", "three": "Tony"]
    
    // Displaying original dictionary
    print("Original dictionary: ", someDictionary)
    
    // Changing the value
    someDictionary["two"] = "Priya"
    
    // Displaying updated dictionary
    print("Updated dictionary: ", someDictionary)

    Output:

    Original dictionary:  ["two": "Rohit", "one": "Mohit", "three": "Tony"]
    Updated dictionary:  ["two": "Priya", "one": "Mohit", "three": "Tony"]

    Accessing Elements of a Dictionary

    You can access the keys and values separately from the dictionary.

    1. Accessing Keys: To access the keys of a dictionary, use the keys property, which returns all the keys from the dictionary.

    Syntax:

    Dictionary_name.keys

    Example:

    // Accessing all the keys from the dictionary
    var result = Array(someDictionary.keys)
    
    // Displaying keys
    print("Keys:", result)

    Output:

    Keys: ["two", "three", "one"]

    2. Accessing Values: To access the values of a dictionary, use the values property, which returns all the values from the dictionary.

    Syntax:

    Dictionary_name.values

    Example:

    // Accessing all the values from the dictionary
    var result = Array(someDictionary.values)
    
    // Displaying values
    print("Values:", result)

    Output:

    Values: ["Priya", "Mohit", "Tony"]

    Iterating Over a Dictionary

    You can iterate over a dictionary using a for-in loop. The key-value pairs’ order is not guaranteed, as dictionaries are unordered collections.

    Syntax:

    for (key, value) in someDictionary {}

    Example:

    // Iterating over a dictionary
    for (key, value) in someDictionary {
        print("\(key): \(value)")
    }

    Output:

    two: Priya
    three: Tony
    one: Mohit

    Creating a Dictionary from Two Arrays

    You can create a dictionary from two arrays of the same size, where the first array represents the keys and the second array represents the values.

    Syntax:

    var someDictionary = Dictionary(uniqueKeysWithValues: zip(someArray, someArray2))

    Example:

    // Creating arrays
    var someArray = ["one", "two", "three"]
    var someArray2 = ["Mohit", "Rohit", "Tony"]
    
    // Creating a dictionary from arrays
    var someDictionary = Dictionary(uniqueKeysWithValues: zip(someArray, someArray2))
    
    // Displaying the dictionary
    print(someDictionary)

    Output:

    ["one": "Mohit", "two": "Rohit", "three": "Tony"]

    Removing Items from a Dictionary

    To remove a key-value pair from a dictionary, use the removeValue(forKey:) method. This method returns the value associated with the removed key or nil if the key is not found.

    Syntax:

    let areEqual = mySet1 == mySet2

    Example:

    // Removing key-value pair from dictionary
    someDictionary.removeValue(forKey: "one")
    
    // Displaying updated dictionary
    print(someDictionary)

    Output:

    ["two": "Rohit", "three": "Tony"]

    Converting a Dictionary to an Array

    You can convert a dictionary into an array of key-value pairs. This results in two arrays: one for keys and another for values.

    Syntax:

    Array(dictionary)

    Example:

    // Converting dictionary to arrays
    var dictArray1 = Array(someDictionary.keys)
    var dictArray2 = Array(someDictionary.values)
    
    // Displaying arrays
    print(dictArray1)
    print(dictArray2)

    Output:

    ["two", "three", "one"]
    ["Rohit", "Tony", "Mohit"]

    Dictionary Properties

    count Property: The count property returns the number of key-value pairs in the dictionary.

    Syntax:

    dictionary.count

    Example:

    var planets = ["Mercury": "Closest to the sun", "Venus": "Second closest", "Earth": "Third closest"]
    print("Total planets: \(planets.count)")

    Output:

    Total planets: 3

    isEmpty Property: The isEmpty property checks if a dictionary is empty or contains key-value pairs.

    Syntax:

    dictionary.isEmpty

    Example:

    var emptyDictionary = [String: String]()
    
    print("Is the dictionary empty? \(emptyDictionary.isEmpty)")  // true
    print("Is the planets dictionary empty? \(planets.isEmpty)")  // false

    Output:

    Is the dictionary empty? true
    Is the planets dictionary empty? false

  • Swift Arrays

    Swift Structures

    An array is a collection that can store multiple values of the same data type. Arrays in Swift are powerful because they allow you to handle collections of data efficiently. For example, if we want to store the marks of multiple students, using a list of variables would not be practical. Instead, an array can hold these marks in a single structure.

    Declaring an Array

    In Swift, you can declare an array with specific data types. Here’s the basic syntax:

    var myArray: [Int] = [10, 20, 30]

    Alternatively, Swift can infer the data type:

    var myArray = [10, 20, 30]

    If you want to create an empty array, use the following syntax:

    var myArray: [Int] = []
    Initializing an Array with Default Values

    Swift allows you to create an array with a default value and a specified size using:

    var myArray = Array(repeating: "Swift", count: 3)

    This creates an array with three "Swift" values.

    Example:

    var myArray = Array(repeating: "Swift", count: 3)
    print("myArray:", myArray)

    Output:

    myArray: ["Swift", "Swift", "Swift"]
    Accessing and Modifying Array Elements

    To access array elements, use the index:

    var myArray: [Int] = [10, 20, 19, 29, 45]
    print("Element at index 0:", myArray[0]) // Output: 10
    print("Element at index 3:", myArray[3]) // Output: 29

    To modify array elements, you can use the same indexing:

    var myArray: [String] = ["Swift", "Xcode", "iOS"]
    myArray[0] = "SwiftUI"
    myArray[1] = "Playgrounds"
    print("myArray:", myArray)

    Output:

    myArray: ["SwiftUI", "Playgrounds", "iOS"]
    Inserting and Appending Elements

    To insert an element at a specific index:

    var myArray: [String] = ["Swift", "Xcode"]
    myArray.insert("iOS", at: 1)
    print("myArray:", myArray)

    Output:

    myArray: ["Swift", "iOS", "Xcode"]

    To add elements to the end of an array:

    myArray.append("iPad")
    print("myArray:", myArray)

    Output:

    myArray: ["Swift", "iOS", "Xcode", "iPad"]
    Concatenating Arrays

    You can concatenate two arrays using the + operator:

    var array1: [Int] = [1, 2, 3]
    var array2: [Int] = [4, 5, 6]
    var combinedArray = array1 + array2
    print("combinedArray:", combinedArray)

    Output:

    combinedArray: [1, 2, 3, 4, 5, 6]
    Iterating Over an Array

    To iterate over each element in an array, use a for-in loop:

    var myArray = ["Swift", "Xcode", "iOS"]
    for element in myArray {
        print(element)
    }

    Output:

    Swift
    Xcode
    iOS
    Counting Elements in an Array

    You can easily count the number of elements in an array using the count property:

    var myArray: [Int] = [10, 20, 30]
    print("Number of elements:", myArray.count)

    Output:

    Number of elements: 3
    Removing Elements from an Array

    To remove an element from a specific index:

    var myArray: [String] = ["Swift", "Xcode", "iOS", "iPad"]
    myArray.remove(at: 2)
    print("myArray after removal:", myArray)

    Output:

    myArray after removal: ["Swift", "Xcode", "iPad"]

    If we remove "Apple" from the array:

    var myArray: [String] = ["Orange", "Apple", "Banana", "Grapes"]
    if let index = myArray.firstIndex(of: "Apple") {
        myArray.remove(at: index)
    }
    print("myArray after removing 'Apple':", myArray)

    Output:

    myArray after removing 'Apple': ["Orange", "Banana", "Grapes"]

    Arrays Properties

    An array is one of the most commonly used data types due to the benefits it provides in writing efficient programs. Similar to other programming languages, in Swift, an array is a collection of similar data types that stores data in an ordered list.

    • When you assign an array to a variable, it becomes mutable, meaning you can add, remove, or modify the elements in the array.
    • When you assign an array to a constant, it becomes immutable, meaning you cannot change its size or modify its elements.
    // Different ways to create arrays in Swift
    var myArray = [Type](count: NumberOfItems, repeatedValue: Value)
    var myArray: [Int] = [10, 20, 30]
    var myArray: Array<String> = Array()

    Example of Array Creation:

    var programmingLanguages = ["Swift", "Python", "JavaScript"]
    var numbers = [Int](count: 5, repeatedValue: 1)
    Commonly Used Array Properties

    1. Array.count Property
    The count property is used to find the total number of elements in the array, whether they are numbers or strings.

    Syntax:

    Array.count

    Example:

    let array1 = [10, 20, 30, 40, 50]
    let array2 = ["Apple", "Banana", "Cherry"]
    let array3: [Int] = []
    
    let count1 = array1.count
    let count2 = array2.count
    let count3 = array3.count
    
    print("Total elements in array1: \(count1)")
    print("Total elements in array2: \(count2)")
    print("Total elements in array3: \(count3)")

    Output:

    Total elements in array1: 5
    Total elements in array2: 3
    Total elements in array3: 0

    2. Array.first Property
    The first property retrieves the first element of the array.

    Syntax:

    Array.first

    Example: 

    let array1 = [12, 24, 36, 48]
    let array2 = ["Red", "Green", "Blue"]
    let array3: [Int] = []
    
    let first1 = array1.first
    let first2 = array2.first
    let first3 = array3.first
    
    print("First element of array1: \(first1 ?? -1)") // Optional handling
    print("First element of array2: \(first2 ?? "None")")
    print("First element of array3: \(first3 ?? -1)")

    Output:

    First element of array1: Optional(12)
    First element of array2: Optional("Red")
    First element of array3: nil

    3. Array.last Property
    The last property retrieves the last element of the array.

    Syntax:

    Array.last

    Example:

    let array1 = [1, 3, 5, 7]
    let array2 = ["Monday", "Tuesday", "Wednesday"]
    let array3: [String] = []
    
    let last1 = array1.last
    let last2 = array2.last
    let last3 = array3.last
    
    print("Last element of array1: \(last1 ?? -1)")
    print("Last element of array2: \(last2 ?? "None")")
    print("Last element of array3: \(last3 ?? "Empty")")

    Output:

    Last element of array1: Optional(7)
    Last element of array2: Optional("Wednesday")
    Last element of array3: nil

    4. Array.isEmpty Property
    The isEmpty property checks if the array is empty. It returns true if the array is empty and false otherwise.

    Syntax:

    Array.isEmpty

    Example:

    let array1 = [5, 10, 15, 20]
    let array2 = [String]()
    let array3 = ["Apple", "Orange"]
    
    let empty1 = array1.isEmpty
    let empty2 = array2.isEmpty
    let empty3 = array3.isEmpty
    
    print("Is array1 empty? \(empty1)")
    print("Is array2 empty? \(empty2)")
    print("Is array3 empty? \(empty3)")

    Output:

    Is array1 empty? false
    Is array2 empty? true
    Is array3 empty? false

    How to Store Values in Arrays?

    An array is a collection of elements having the same data type. Normally, to store values of a specific data type, we use variables. For example, to store marks for 5 students, we can create 5 variables. However, for a class with 50 or more students, creating separate variables for each student is inefficient and makes the code less readable. To store a large number of elements of the same type, we use arrays. Array elements can be accessed using index numbers, starting from 0 in Swift.

    Below, we explore various methods to store values in an array using Swift programming.

    1. Initializing an Array: You can initialize an array with elements directly at the time of declaration.

    Syntax:

    var myArray: [DataType] = [value1, value2, value3, ...]

    Example:

    // Swift program to store values in arrays
    
    // Initializing an array of integer type
    var numbers: [Int] = [1, 3, 5, 7]
    
    // Initializing another array of character type
    var characters: [Character] = ["A", "B", "C", "D"]
    
    // Print arrays
    print("Numbers Array: \(numbers)")
    print("Characters Array: \(characters)")

    Output:

    Numbers Array: [1, 3, 5, 7]
    Characters Array: ["A", "B", "C", "D"]

    Example 2:

    // Swift program to store values in arrays
    
    // Initializing an array of float type
    var decimals: [Float] = [1.2, 5.32, 5.56, 7.15]
    
    // Initializing another array of string type
    var words: [String] = ["Hello", "World"]
    
    // Print arrays
    print("Decimals Array: \(decimals)")
    print("Words Array: \(words)")

    Output:

    Decimals Array: [1.2, 5.32, 5.56, 7.15]
    Words Array: ["Hello", "World"]

    2. Using append() Method: The append() method allows you to add an element to the end of the array.

    Syntax:

    myArray.append(value)

    Example:

    // Swift program to add values to arrays using append()
    
    // Initializing an array of integer type
    var numbers: [Int] = [1, 3]
    
    // Adding elements using append()
    numbers.append(5)
    numbers.append(7)
    
    // Initializing another array of character type
    var characters: [Character] = ["X", "Y"]
    
    // Adding elements using append()
    characters.append("Z")
    characters.append("W")
    
    // Print arrays
    print("Numbers Array: \(numbers)")
    print("Characters Array: \(characters)")

    Output:

    Numbers Array: [1, 3, 5, 7]
    Characters Array: ["X", "Y", "Z", "W"]

    3. Using insert() Method: The insert() method adds an element to a specified index in the array.

    Syntax:

    myArray.insert(value, at: index)

    Example:

    // Swift program to insert values into arrays
    
    // Initializing an array of integers
    var numbers: [Int] = [1, 3]
    
    // Inserting elements at specific indices
    numbers.insert(5, at: 1)
    numbers.insert(7, at: 2)
    
    // Initializing another array of characters
    var characters: [Character] = ["M", "N"]
    
    // Inserting elements at specific indices
    characters.insert("O", at: 1)
    characters.insert("P", at: 2)
    
    // Print arrays
    print("Numbers Array: \(numbers)")
    print("Characters Array: \(characters)")

    Output:

    Numbers Array: [1, 5, 7, 3]
    Characters Array: ["M", "O", "P", "N"]

    How to Remove the First element from an Array in Swift?

    In Swift, an array is an ordered collection that stores values of the same type. For example, an array declared to hold integers cannot store floating-point numbers. Arrays in Swift can store duplicate values.

    When an array is assigned to a variable, it is mutable, meaning you can modify its contents and size. However, when an array is assigned to a constant, it becomes immutable, and you cannot modify it.

    Removing Elements in Swift Arrays

    You can remove the first element from a Swift array using the removeFirst() function. Additionally, you can use this function to remove multiple elements from the start of the array by specifying the number of elements to remove as an argument.

    Syntax

    arrayName.removeFirst(x: Int)

    Example 1: Removing a Single Element

    import Swift
    
    // String array of authors' names
    var authors = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
    
    print("Authors before removing the first element: \(authors)")
    
    // Remove the first element
    authors.removeFirst()
    
    print("Authors after removing the first element: \(authors)")
    
    // Integer array of article IDs
    var articleIDs = [101, 202, 303, 404, 505]
    
    print("\nArticle IDs before removing the first element: \(articleIDs)")
    
    // Remove the first element
    articleIDs.removeFirst()
    
    print("Article IDs after removing the first element: \(articleIDs)")

    Example:

    Authors before removing the first element: ["Alice", "Bob", "Charlie", "Diana", "Eve"]
    Authors after removing the first element: ["Bob", "Charlie", "Diana", "Eve"]
    
    Article IDs before removing the first element: [101, 202, 303, 404, 505]
    Article IDs after removing the first element: [202, 303, 404, 505]

    How to count the elements of an Array in Swift?

    Swift Arrays: Counting Elements

    In Swift, an array is an ordered, generic collection that stores values of the same type, such as integers, strings, or floats. You cannot mix data types in a single array. Arrays can also store duplicate values.

    Arrays can be either mutable or immutable:

    • Mutable arrays: Assigned to variables, allowing modifications.
    • Immutable arrays: Assigned to constants, preventing modifications.
    arrayName.count

    Example:

    import Swift
    
    // String array of authors' names
    var authors = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]
    
    // Counting the total number of authors
    var result1 = authors.count
    
    // Displaying the result
    print("Total number of authors:", result1)
    
    // Empty integer array for employee IDs
    var employeeIDs = [Int]()
    
    // Counting the total number of employees
    var result2 = employeeIDs.count
    
    // Displaying the result
    print("Total number of employees:", result2)

    Output:

    Total number of authors: 6
    Total number of employees: 0

    How to Reverse an Array in Swift?

    Swift Arrays: Reversing Elements

    In Swift, an array is a generic, ordered collection used to store values of the same type, such as integers, floats, or strings. You cannot mix types within an array. Arrays can also store duplicate values.

    Arrays can be:

    • Mutable: When assigned to a variable, allowing you to modify their contents and size.
    • Immutable: When assigned to a constant, preventing any modifications.

    Syntax:

    arrayName.reverse()

    Example:

    import Swift
    
    // Float array of numbers
    var numbers = [10.5, 3.14, 7.89, 42.0, 1.99, 99.9]
    
    print("Array before reversing:", numbers)
    
    // Reversing the array using reverse() function
    numbers.reverse()
    
    print("Array after reversing:", numbers)

    Output:

    Array before reversing: [10.5, 3.14, 7.89, 42.0, 1.99, 99.9]
    Array after reversing: [99.9, 1.99, 42.0, 7.89, 3.14, 10.5]

    Swift Array joined() function

    In Swift, arrays are ordered collections of values of the same type, such as integers, strings, or floats. You cannot store values of different types in the same array (e.g., a string array can only contain strings). Arrays can store duplicate values and are either mutable (if assigned to a variable) or immutable (if assigned to a constant).

    The joined() function in Swift allows you to concatenate all the elements of a string array into a single string. You can use an optional separator to specify how the elements are joined.

    Syntax:

    import Swift
    
    // String array of words
    var words = ["Hello", "and", "welcome", "to", "the", "Swift", "Tutorial"]
    
    // Joining all elements with a space separator
    var result1 = words.joined(separator: " ")
    
    print("New String 1:", result1)
    
    print("----------------------")
    
    // Joining all elements with a hyphen separator
    var result2 = words.joined(separator: "-")
    
    print("New String 2:", result2)

    Output:

    New String 1: Hello and welcome to the Swift Tutorial
    ----------------------
    New String 2: Hello-and-welcome-to-the-Swift-Tutorial

    Sorting an Array in Swift+

    In Swift, arrays are one of the most commonly used collections. An array is an ordered collection of elements of the same type, such as integers, strings, or floats. Swift ensures type safety by not allowing arrays to store elements of different types (e.g., an array of integers cannot hold a string value).

    Arrays in Swift are generic, meaning they can store duplicate values of the same type.

    • If an array is assigned to a variable, it is mutable—you can modify its contents and size.
    • If an array is assigned to a constant, it is immutable—you cannot modify its contents or size.
    • Swift provides a way to sort arrays in both ascending and descending order using the sort() method. This method allows customization of sorting using the < (less than) and > (greater than) operators.

    Syntax:

    arrayName.sort(by: operator)

    Parameters:

    • arrayName: The name of the array.
    • operator: An optional parameter (< for ascending or > for descending).

    Return Value: The sort() method does not return a new array; instead, it modifies the original array.

    Sorting an Array

    Example 1Default Sorting (Ascending Order)

    import Swift
    
    var AuthorName = ["Rohit", "Poonam", "Anu", "Susmita", "Buvan", "Mohit"]
    
    print("Author's name before sorting:", AuthorName)
    
    // Sorting in ascending order
    AuthorName.sort()
    
    print("Author's name after sorting:", AuthorName)
    
    var ArticleNumber = [23, 1, 90, 3, 56, 23, 0, 6, 12]
    
    print("----------------------")
    
    print("Article numbers before sorting:", ArticleNumber)
    
    // Sorting in ascending order
    ArticleNumber.sort()
    
    print("Article numbers after sorting:", ArticleNumber)

    Output:

    Author's name before sorting: ["Rohit", "Poonam", "Anu", "Susmita", "Buvan", "Mohit"]
    Author's name after sorting: ["Anu", "Buvan", "Mohit", "Poonam", "Rohit", "Susmita"]
    ----------------------
    Article numbers before sorting: [23, 1, 90, 3, 56, 23, 0, 6, 12]
    Article numbers after sorting: [0, 1, 3, 6, 12, 23, 23, 56, 90]
    Sorting in Ascending Order (Explicitly Specifying < Operator)
    import Swift
    
    var AuthorName = ["Sumit", "Neha", "Anu", "Susmita", "Buvan", "Govind"]
    
    print("Author's name before sorting:", AuthorName)
    
    // Sorting explicitly in ascending order
    AuthorName.sort(by: <)
    
    print("Author's name after sorting:", AuthorName)
    
    var ArticleNumber = [3, 20, 10, 3, 86, 23, 0, 699, 12]
    
    print("----------------------")
    
    print("Article numbers before sorting:", ArticleNumber)
    
    // Sorting explicitly in ascending order
    ArticleNumber.sort(by: <)
    
    print("Article numbers after sorting:", ArticleNumber)

    Output:

    Author's name before sorting: ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
    Author's name after sorting: ["Susmita", "Punit", "Neha", "Govind", "Fiza", "Amu"]
    ----------------------
    Article numbers before sorting: [3, 20, 10, 3, 86, 23, 0, 699, 12]
    Article numbers after sorting: [699, 86, 23, 20, 12, 10, 3, 3, 0]
    Sorting in Descending Order

    Example:

    import Swift
    
    var AuthorName = ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
    
    print("Author's name before sorting:", AuthorName)
    
    // Sorting in descending order
    AuthorName.sort(by: >)
    
    print("Author's name after sorting:", AuthorName)
    
    var ArticleNumber = [3, 20, 10, 3, 86, 23, 0, 699, 12]
    
    print("----------------------")
    
    print("Article numbers before sorting:", ArticleNumber)
    
    // Sorting in descending order
    ArticleNumber.sort(by: >)
    
    print("Article numbers after sorting:", ArticleNumber)

    Output:

    Author's name before sorting: ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
    Author's name after sorting: ["Susmita", "Punit", "Neha", "Govind", "Fiza", "Amu"]
    ----------------------
    Article numbers before sorting: [3, 20, 10, 3, 86, 23, 0, 699, 12]
    Article numbers after sorting: [699, 86, 23, 20, 12, 10, 3, 3, 0]

    How to Swap Array items in Swift?

    Swift provides various generic collections, including sets, dictionaries, and arrays. An array is an ordered collection used to store values of the same type, such as strings, integers, or floats. Swift enforces type safety, so you cannot store values of a different type in an array. For example, if an array is of type Int, adding a Float value to it will result in an error. Arrays also allow duplicate values of the same type.

    In Swift, arrays can be mutable or immutable:

    • Mutable: You can modify their contents.
    • Immutable: You cannot modify their contents.

    Syntax:

    arrayName.swapAt(index1, index2)

    Parameters:

    • arrayName: The name of the array.
    • index1: The index of the first element to swap.
    • index2: The index of the second element to swap.

    Return Value:

    The swapAt() method does not return a value. It directly modifies the array by swapping the specified elements.

    Example:

    import Swift
    
    // Creating an array of numbers
    // The array is of type Float
    var newNumber = [23.034, 1.90, 9.1, 32.34, 560.44, 21.23]
    
    print("Array before swapping:", newNumber)
    
    // Swapping elements at positions 1 and 2 using swapAt() method
    newNumber.swapAt(1, 2)
    
    // Displaying the result
    print("Array after swapping:", newNumber)

    Output:

    Array before swapping: [23.034, 1.9, 9.1, 32.34, 560.44, 21.23]
    Array after swapping: [23.034, 9.1, 1.9, 32.34, 560.44, 21.23]
  • Swift Sets

    Sets

    set is a collection of unique elements. By unique, we mean no two elements in a set can be equal. Unlike sets in C++, elements of a set in Swift are not arranged in any particular order. Internally, a set in Swift uses a hash table to store elements. For instance, consider the task of finding the number of unique marks scored by students in a class. Let a list of marks be:
    list = [98, 80, 86, 80, 98, 98, 67, 90, 67, 84].
    In this list:

    • 98 occurs three times,
    • 80 and 67 occur twice,
    • 8486, and 90 occur only once.
    Creating Sets

    You can create an empty set using the following syntax, explicitly specifying the data type of the set:

    Syntax:

    var mySet = Set<data_type>()

    Here, data_type is the type of data the set will store, such as IntCharacterString, etc.

    Example: Creating Empty Sets

    // Swift program to create empty sets and add elements
    import Foundation
    
    // Creating an empty set of Int data type
    var mySet1 = Set<Int>()
    mySet1.insert(5)
    mySet1.insert(15)
    mySet1.insert(5)
    print("mySet1:", mySet1)
    
    // Creating an empty set of String data type
    var mySet2 = Set<String>()
    mySet2.insert("Apple")
    mySet2.insert("Banana")
    print("mySet2:", mySet2)
    
    // Creating an empty set of Character data type
    var mySet3 = Set<Character>()
    mySet3.insert("A")
    mySet3.insert("B")
    print("mySet3:", mySet3)
    
    // Creating an empty set of Boolean data type
    var mySet4 = Set<Bool>()
    mySet4.insert(true)
    mySet4.insert(false)
    print("mySet4:", mySet4)

    Output:

    mySet1: [15, 5]
    mySet2: ["Apple", "Banana"]
    mySet3: ["B", "A"]
    mySet4: [true, false]
    Initialization of Sets

    Method 1: Implicitly determined data type: You can initialize a set without explicitly specifying its data type.

    Syntax:

    var mySet: Set = [value1, value2, value3, …]

    Example:

    var mySet1: Set = [10, 20, 30, 40]
    var mySet2: Set = ["Red", "Blue", "Green"]
    var mySet3: Set = ["A", "B", "C"]
    
    print("mySet1:", mySet1)
    print("mySet2:", mySet2)
    print("mySet3:", mySet3)

    Output:

    mySet1: [10, 30, 40, 20]
    mySet2: ["Green", "Blue", "Red"]
    mySet3: ["B", "A", "C"]

    Method 2: Explicitly specifying data type: You can initialize a set and explicitly define its data type:

    Syntax:

    var mySet: Set<data_type> = [value1, value2, value3, …]

    Example: Explicit Initialization

    var mySet1: Set<Int> = [1, 2, 3, 4, 5]
    var mySet2: Set<String> = ["Dog", "Cat", "Bird"]
    var mySet3: Set<Character> = ["X", "Y", "Z"]
    
    print("mySet1 elements are:")
    for element in mySet1 {
        print(element)
    }
    
    print("\nmySet2 elements are:")
    for element in mySet2 {
        print(element)
    }
    
    print("\nmySet3 elements are:")
    for element in mySet3 {
        print(element)
    }

    Output:

    mySet1 elements are:
    1
    2
    3
    4
    5
    
    mySet2 elements are:
    Bird
    Cat
    Dog
    
    mySet3 elements are:
    X
    Y
    Z

    Method 3: Using insert()The insert() method allows you to add elements to a set.

    Syntax:

    mySet.insert(value)
    Example: Adding Elements Using insert()
    swift
    Copy code

    Output:

    Elements of mySet are:
    Phone
    Laptop
    Tablet
    Iterating Over a Set

    1. Using for-in Loop: Directly access each element in a set.

    myArray.append("iPad")
    print("myArray:", myArray)

    Output:

    // Output
    mySet1 elements are :
    15
    21
    1
    4
    13
    6
    
    mySet2 elements are :
    Kunal
    Honey
    Bhuwanesh
    Aarush
    Nawal

    2. Using index(_:offsetBy:)Access elements by their index, useful for specific ordering.

    var index = 0
    while index < mySet.count {
        print(mySet[mySet.index(mySet.startIndex, offsetBy: index)])
        index += 1
    }

    Output:

    // Output
    mySet1 elements:
    10
    4
    9
    3
    8
    
    mySet2 elements:
    3.123
    1.123
    9.123
    4.123
    8.123
    Comparing Sets

    1. Custom Comparison (contains() method): Iterate and compare each element between two sets for equality

    func Compare(mySet1: Set<Int>, mySet2: Set<Int>) -> Bool {
        return mySet1.allSatisfy { mySet2.contains($0) } &&
               mySet2.allSatisfy { mySet1.contains($0) }
    }

    Output:

    // Output
    Are myset1 and myset2 equal ? false
    Are myset1 and myset3 equal ? false
    Are myset2 and myset3 equal ? true

    2. Using == Operator: Directly compare sets for equality.

    let areEqual = mySet1 == mySet2

    Output:

    // Output
    Are myset1 and myset2 equal ? true
    Are myset1 and myset3 equal ? false
    Are myset2 and myset2 equal ? false
    Set Operations

    1. Union:Combine elements of two sets.

    var myArray: [String] = ["Swift", "Xcode", "iOS", "iPad"]
    myArray.remove(at: 2)
    print("myArray after removal:", myArray)

    Output:

    // Output
    Union set: [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 35, 40, 45, 50]

    2. Intersection: Find common elements.

    let intersectionSet = mySet1.intersection(mySet2)

    Output:

    // Output
    Intersection set: [15, 30]

    3. Subtraction: Elements in one set but not the other.

    let subtractionSet = mySet1.subtracting(mySet2)

    Output:

    // Output
    Subtraction set: [3, 6, 9, 12, 18, 21, 24, 27]

    4. Symmetric Difference: Elements unique to each set.

    let symmetricDifferenceSet = mySet1.symmetricDifference(mySet2)

    Output:

    // Output
    Symmetric difference set: [3, 5, 6, 9, 10, 12, 18, 20, 21, 24, 25, 27, 35, 40, 45, 50]

    5. Subset Check:Determine if one set is a subset of another.

    let isSubset = mySet1.isSubset(of: mySet2)

    Output: 

    // Output
    Is mySet1 a subset of mySet2 ?: false
    Modifying Sets

    1. Adding Elements:

    mySet.insert(newElement)

    2. Removing Elements:

    mySet.remove(elementToRemove)

    3. Clearing All Elements:

    mySet.removeAll()

    4. Check Membership:

    if mySet.contains(specificElement) { /*...*/ }

    How to remove first element from the Set in Swift?

    Swift Set and the removeFirst() Function

    set in Swift is a generic collection that stores unordered values of the same type. It ensures all elements are unique, meaning no duplicates are allowed. Sets are particularly useful when the order of values doesn’t matter, and only uniqueness is required. Internally, a set uses a hash table for storing its elements.

    Sets can be mutable (modifiable) or immutable (fixed). To remove the first element from a set, you can use the removeFirst() method. Since sets are unordered, this method removes and returns a random element from the set.

    Syntax:

    setName.removeFirst()

    Example:

    // Swift program to remove an element from a set
    import Swift
    
    // Creating a set of numbers
    var numbers: Set = [12, 45, 78, 23, 56, 89]
    
    // Displaying the original set
    print("Original Set:", numbers)
    
    // Removing the first element
    let removedElement = numbers.removeFirst()
    
    // Displaying the removed element
    print("Removed Element:", removedElement)
    
    // Displaying the set after removal
    print("Final Set:", numbers)

    Output:

    Original Set: [45, 12, 78, 23, 56, 89]
    Removed Element: 45
    Final Set: [12, 78, 23, 56, 89]

    Swift Set and the removeAll() Function

    set in Swift is a generic, unordered collection used to store values of the same type. You cannot mix data types within a set—for example, a string set can only store string values, not integers. Sets are particularly useful when the order of elements is irrelevant and only unique values are required. Internally, sets rely on a hash table for efficient storage.

    Sets can be mutable (modifiable) or immutable (fixed). To remove all elements from a set, you can use the removeAll() method. This method clears the set entirely, leaving it empty.

    Syntax:

    setName.removeAll()

    Example:

    // Swift program to remove all elements from a set
    import Swift
    
    // Creating a set of author's names
    var authorNames: Set = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
    
    // Displaying the original set
    print("Original Set:", authorNames)
    
    // Removing all elements
    authorNames.removeAll()
    
    // Displaying the set after removal
    print("Final Set:", authorNames)

    Output:

    Original Set: ["Diana", "Eve", "Alice", "Charlie", "Bob"]
    Final Set: []

    How to check if the set contains a given element in Swift?

    Swift supports generic collections, and sets are one of them. A set is used to store unordered values of the same type. For instance, if a set is of integer type, it can only store integer values, not strings or other types. Sets are preferred over arrays when the order of values is irrelevant or when you need to store unique values only. Sets do not allow duplicate elements and use a hash table for storage.

    In Swift, you can easily check if a set contains a specific element using the contains() function. This function is case-sensitive; for example, "Mohan" and "mohan" are considered different values.

    Syntax:

    setName.contains(element)
    // Swift program to check if a specified element is present in the set
    import Swift
    
    // Creating a set of ranks
    var ranks: Set = [10, 20, 30, 40, 50, 60]
    
    // Checking if a specific element is present in the set
    if ranks.contains(15) {
        print("15 is present in the set")
    } else {
        print("15 is not present in the set")
    }
    
    // Checking for another element in the set
    if ranks.contains(40) {
        print("40 is present in the set")
    } else {
        print("40 is not present in the set")
    }

    Output:

    15 is not present in the set
    40 is present in the set

    How to count the elements of a Set in Swift?

    Swift provides various types of generic collections, with set being one of them. A set is a collection used to store unordered values of the same type. Unlike arrays, sets do not allow duplicate values, ensuring that all elements are unique. Internally, sets use a hash table for storing elements efficiently.

    To determine the number of elements in a set, you can use the count property. This property returns the total number of values in the set.

    Syntax:

    setName.count

    Example:

    // Swift program to find the total number of elements in a set
    import Swift
    
    // Creating a set of employee salaries
    var employeeSalaries: Set = [45000, 28000, 36000, 52000, 60000, 72000]
    
    // Counting the total number of elements
    let totalCount1 = employeeSalaries.count
    
    // Displaying the result
    print("Total number of elements in the set:", totalCount1)
    
    // Creating an empty set of integers
    var emptySet = Set<Int>()
    
    // Counting the total number of elements in the empty set
    let totalCount2 = emptySet.count
    
    // Displaying the result
    print("Total number of elements in the empty set:", totalCount2)

    Output:

    Total number of elements in the set: 6
    Total number of elements in the empty set: 0

    Sorting a Set in Swift

    In Swift, a set is a generic collection used to store unordered unique values of the same type. Sets are useful when the order of elements is irrelevant or when duplicates need to be avoided. Internally, they use a hash table for storage.

    You can sort the elements of a set using the sorted() function. By default, this function sorts the elements in ascending order. However, you can sort them in descending order by passing the greater-than operator (>). Similarly, the less-than operator (<) explicitly sorts elements in ascending order.

    Syntax:

    setName.sorted(by: operatorValue)

    Example:

    // Swift program to sort the elements of a set
    import Swift
    
    // Creating a set of employee names
    var employeeNames: Set = ["Amit", "Pooja", "Raj", "Meera", "Vikas"]
    
    print("Employee names before sorting:", employeeNames)
    
    // Sorting the elements of the set
    let sortedNames = employeeNames.sorted()
    
    // Displaying the sorted result
    print("Employee names after sorting:", sortedNames)

    Output:

    Employee names before sorting: ["Raj", "Amit", "Meera", "Pooja", "Vikas"]
    Employee names after sorting: ["Amit", "Meera", "Pooja", "Raj", "Vikas"]

    How to check if a set is empty in Swift?

    Swift provides a built-in property isEmpty to check if a set contains elements or not. A set in Swift is used to store unordered, unique values of the same type. When isEmpty is called, it returns true if the set contains no elements and false otherwise.

    Syntax:

    arrayName.removeFirst(x: Int)
    asetName.isEmpty

    Example :

    // Swift program to check if the given set is empty or not
    import Swift
    
    // Creating a set of employee salaries
    var employeeSalaries: Set = [30000, 12200, 14000, 67800, 10000, 90000]
    
    // Checking if the set is empty using the isEmpty property
    let isEmployeeSalariesEmpty = employeeSalaries.isEmpty
    
    // Displaying the result
    print("Is the employeeSalaries set empty?", isEmployeeSalariesEmpty)
    
    // Creating an empty set of integer type
    var employees = Set<Int>()
    
    // Checking if the set is empty using the isEmpty property
    let isEmployeesEmpty = employees.isEmpty
    
    // Displaying the result
    print("Is the employees set empty?", isEmployeesEmpty)

    Output:

    Is the employeeSalaries set empty? false
    Is the employees set empty? true

    How to shuffle the elements of a set in Swift?

    In Swift, a set is an unordered collection used to store unique elements of the same type. Sets do not allow duplicate values and use a hash table to store elements. Sets can be mutable or immutable based on whether they are assigned to a variable or constant. Swift provides the shuffled() function to shuffle the elements in a set, returning a new set with the elements in random order.

    Syntax:

    setName.shuffled()

    Example:

    // Swift program to shuffle all the elements from the set
    import Swift
    
    // Creating a set of author ratings
    var authorRatings: Set = [2, 458, 65, 8, 76, 4, 982, 3, 4, 5]
    
    // Displaying the original set
    print("Original Set:", authorRatings)
    
    // Shuffle all the elements of the set using the shuffled() function
    let shuffledRatings = authorRatings.shuffled()
    
    // Displaying the shuffled elements
    print("Shuffled elements:", shuffledRatings)

    Output:

    Original Set: [458, 76, 982, 8, 5, 4, 3, 65, 2]
    Shuffled elements: [65, 5, 4, 982, 76, 8, 2, 3, 458]

    Difference Between Sets and Arrays

    An array is a linear data structure used to store multiple elements in a single variable. These elements are stored in contiguous memory, and each element can be accessed using an index. Arrays can store elements of the same type.

    Syntax:

    var arr: [DataType] = [value1, value2, value3, ..., valueN]

    Example:

    // Swift program to illustrate array
    
    // Creating and initializing an Array with Integer Values
    var arr: [Int] = [1, 2, 3, 4, 5]
    
    // Display the array
    print(arr)

    Output:

    [1, 2, 3, 4, 5]

    Set in Swift

    set is a data structure that stores unique elements, meaning no duplicate values are allowed. Unlike arrays, sets automatically eliminate duplicate elements. Sets also support operations like union, intersection, and

    // Swift program to illustrate set
    
    // Creating and initializing set of Integer Values
    var set1: Set = [1, 2, 2, 2, 3, 4]
    
    // Creating and initializing set of String Values
    var set2: Set = ["Apple", "Banana", "Orange", "Banana", "Apple"]
    
    // Display the result
    print(set1)
    print(set2)

    Output:

    [3, 4, 1, 2]
    ["Orange", "Banana", "Apple"]
    ArraySet
    Arrays can have elements of any type, but their elements must be ordered.Sets store unique elements of the same type but have no specific order.
    Arrays support both mutable and immutable versions, but they preserve the order of elements when modified.Sets support only unique elements, and adding or removing elements does not affect order since sets are unordered.
    Arrays have a fixed size once initialized.Sets can dynamically grow or shrink as elements are added or removed, with no concern for order.
    You can access elements in an array through indexing (e.g., array[0]).You cannot access elements directly by index in a set; you can only iterate over them.
    Arrays use more memory compared to sets as they store duplicates and maintain order.Sets use less memory because they store only unique elements.
  • Swift Functions

    Decision-Making Statements in Swift

    Decision-making statements in Swift allow the program to choose a specific block of code to execute based on a given condition. These statements evaluate conditions and return a boolean value (true or false). If the condition is true, the associated block of code is executed; otherwise, an alternate block is executed. Swift supports five types of decision-making statements:

    1. Simple if
    2. if-else
    3. if-else if-else
    4. Nested if
    5. Switch

    Simple if Statement

    In Swift, the if statement is used to execute a block of code based on the evaluation of one or more conditions. This type of statement is often referred to as a branch statement. It allows the program to “branch” and execute specific blocks of code when certain conditions are met.

    For example, consider a real-life scenario: you plan to visit a market, and your parent instructs you, “If the plastic containers are on sale, buy two containers.” This is a conditional statement where the action, “buy two containers,” will only occur if the condition, “plastic containers are on sale,” is true.

    Conditional statements are essential in programming as they help introduce logic and decision-making into the code.

    Syntax:

    if (condition) {
        // Body of the if statement
    }
    • The if statement evaluates the condition inside the parentheses ().
    • If the condition evaluates to true, the block of code inside the curly braces {} is executed.
    • If the condition evaluates to false, the block of code is skipped, and the control moves to the next statement.

    Example 1: Basic if Statement

    // Swift program demonstrating the if statement
    
    let val = 30
    
    // Checking if the number is greater than zero
    if (val > 0) {
        // Body of the if statement
        print("The given number is positive.")
    }
    
    // Statement after the if statement (always executed)
    print("Learning if statement in Swift.")

    Output:

    The given number is positive.
    Learning if statement in Swift.

    Explanation:

    • A variable val is declared with a value of 30.
    • The condition val > 0 is evaluated. Since 30 > 0, the condition is true.
    • The code inside the if block is executed, printing: "The given number is positive."
    • The statement after the if block, "Learning if statement in Swift.", is executed regardless of the condition’s result.
    • If val were set to -20, the condition would be false, and only the statement outside the if block would be executed.

    Example 2: Checking Eligibility

    This person is eligible for voting.
    Only 18+ people are eligible for voting.

    Output:

    Integer Type        Min                    Max
    UInt8               0                     255
    UInt16              0                     65535
    UInt32              0                     4294967295
    UInt64              0                     18446744073709551615
    Int8               -128                   127
    Int16              -32768                 32767
    Int32              -2147483648            2147483647
    Int64              -9223372036854775808   9223372036854775807

    Example 3: Using Multiple if Statements

    You can use multiple if statements to check independent conditions instead of using if-else.

    // Swift program demonstrating multiple if statements
    
    let number = 9
    
    // First condition
    if (number % 2 == 0) {
        print("\(number) is an even number")
    }
    
    // Second condition
    if (number % 2 != 0) {
        print("\(number) is an odd number")
    }
    
    // Third condition
    if (number == 9) {
        print("Given number \(number) is equal to the given condition number")
    }

    Output:

    9 is an odd number
    Given number 9 is equal to the given condition number

    Explanation:

    • The first if checks if the number is even (number % 2 == 0), which is false for 9, so this block is skipped.
    • The second if checks if the number is odd (number % 2 != 0), which is true for 9, so it prints: "9 is an odd number."
    • The third if checks if the number equals 9, which is true, so it prints: "Given number 9 is equal to the given condition number."

    If-else Statement

    In Swift, the if-else statement is used to execute a block of code based on a condition and provide an alternative block of code to execute when the condition is not met. This allows programmers to handle conditional logic effectively, ensuring that the program can make decisions dynamically.

    For example, imagine you’re at the market, and your parent says, “If biscuits are on sale, buy biscuits; otherwise, buy chips.” This is a typical if-else condition where one action is executed if the condition is true, and an alternative action is executed if the condition is false.

    Syntax of the if-else Statement

    if (condition) {
        // Body of the if statement
    } else {
        // Body of the else statement
    }
    • The if condition is evaluated.
    • If the condition evaluates to true, the code inside the if block is executed.
    • If the condition evaluates to false, the code inside the else block is executed.
    • The program then continues with the code after the if-else block.

    Examples:

    // Swift program to demonstrate the use of if-else statement
    
    // Declare and initialize a variable
    let val = 40
    
    // Check if the number is equal to 40
    if (val == 40) {
        print("Both the numbers are equal")
    } else {
        print("Both the numbers are not equal")
    }
    
    // Code after if…else statement
    // This statement is always executed
    print("Learning if…else statement in Swift.")

    Output:

    Both the numbers are equal
    Learning if…else statement in Swift.

    Explanation:

    • The variable val is initialized with a value of 40.
    • The condition val == 40 evaluates to true, so the code inside the if block is executed, printing: "Both the numbers are equal".
    • The else block is skipped.
    • The statement after the if-else block, "Learning if…else statement in Swift.", is executed regardless of the condition.
    • If val were set to 45, the condition would evaluate to false, and the output would change to:
    Both the numbers are not equal
    Learning if…else statement in Swift.

    Example 2: Checking Voting Eligibility

    // Swift program to demonstrate the use of if-else statement
    
    // Declare and initialize a variable
    let age = 80
    
    // Checking if age is greater than or equal to 18
    if (age >= 18) {
        print("This person is eligible for voting")
    } else {
        // Executes when the condition is false
        print("This person is not eligible for voting")
    }
    
    // Code after if…else statement
    print("Only 18+ people are eligible for voting")

    Output:

    This person is eligible for voting
    Only 18+ people are eligible for voting

    Explanation:

    • The variable age is initialized with 80.
    • The condition age >= 18 evaluates to true, so the code inside the if block is executed, printing: "This person is eligible for voting".
    • The else block is skipped.
    • The final statement after the if-else block is executed: "Only 18+ people are eligible for voting".
    • If age were set to 16, the output would be:
    This person is not eligible for voting
    Only 18+ people are eligible for voting

    If-else-if Statement

    In Swift, the if-else if-else statement allows you to evaluate multiple conditions and execute the code block corresponding to the first true condition. If none of the conditions are satisfied, the else block executes by default.

    Syntax

    if (condition1) {
        // Block of code for condition1
    } else if (condition2) {
        // Block of code for condition2
    } else if (condition3) {
        // Block of code for condition3
    }
    .
    .
    .
    else {
        // Block of code for all other cases
    }
    • The program checks each condition in sequence.
    • The first condition that evaluates to true will execute its associated block of code.
    • If none of the conditions are true, the else block is executed.

    Example 1: Grading System

    let number = 85
    
    if (number >= 90) {
        print("Grade A")
    } else if (number >= 75) {
        print("Grade B")
    } else if (number >= 60) {
        print("Grade C")
    } else {
        print("Grade D")
    }

    Output:

    Grade B

    Explanation:

    • The variable number is assigned the value 85.
    • The first condition, number >= 90, evaluates to false.
    • The second condition, number >= 75, evaluates to true.
    • The program executes the code block associated with number >= 75, printing: "Grade B".
    • No further conditions are evaluated because one has already been satisfied.

    Example 2: Checking Specific Values

    let number = 20
    
    // Condition 1
    if (number == 10) {
        print("Number is 10")
    }
    // Condition 2
    else if (number == 15) {
        print("Number is 15")
    }
    // Condition 3
    else if (number == 20) {
        print("Number is 20")
    }
    // Default case
    else {
        print("Number is not present")
    }

    Output:

    Number is 20

    Explanation:

    • The variable number is initialized with the value 20.
    • The first condition, number == 10, evaluates to false.
    • The second condition, number == 15, also evaluates to false.
    • The third condition, number == 20, evaluates to true, so the corresponding code block executes, printing: "Number is 20".

    Nested if-else Statement

    In Swift, a nested if-else statement occurs when an if or else block contains another if-else statement inside it. This structure is used when multiple levels of conditions need to be checked. The outer if condition determines if the inner if-else will be executed.

    Syntax:

    // Outer if condition
    if (condition1) {
        // Inner if condition
        if (condition2) {
            // Block of Code for condition2
        } else {
            // Block of Code if condition2 is false
        }
    } else {
        // Inner if condition
        if (condition3) {
            // Block of Code for condition3
        } else {
            // Block of Code if condition3 is false
        }
    }
    • If condition1 is true, the outer if block is executed, and the program checks condition2.
    • If condition1 is false, the program moves to the outer else block and evaluates condition3.
    • Additional layers of if-else can be added as needed.

    Example 1: Finding the Greatest Value

    import Swift
    
    var a = 100
    var b = 200
    var c = 300
    
    // Outer if statement
    if (a > b) {
        // Inner if statement
        if (a > c) {
            // Statement 1
            print("100 is Greater")
        } else {
            // Statement 2
            print("300 is Greater")
        }
    } else {
        // Inner if statement
        if (b > c) {
            // Statement 3
            print("200 is Greater")
        } else {
            // Statement 4
            print("300 is Greater")
        }
    }

    Output:

    300 is Greater

    Explanation:

    1. The outer if condition checks whether a > b. Since 100 > 200 is false, the program skips to the else block.
    2. Inside the else block, the inner if checks whether b > c. Since 200 > 300 is also false, the program executes the inner else block.
    3. The inner else block prints “300 is Greater” because c has the highest value.

    Example 2: Checking Number Properties

    import Swift
    
    var number = 5
    
    // Outer if statement
    if (number >= 0) {
        // Inner if statement
        if (number == 0) {
            // Statement 1
            print("Number is 0")
        } else {
            // Statement 2
            print("Number is greater than 0")
        }
    } else {
        // Statement 3
        print("Number is smaller than 0")
    }

    Output:

    Number is greater than 0

    Switch Statement

    In Swift, a switch statement allows the program to control its flow based on the value of a variable. Once a matching condition is found, the corresponding block is executed, and the control exits the switch block. A default case handles values that do not match any condition, though it’s optional if the switch is exhaustive. Omitting a default in a non-exhaustive switch results in a compile-time error.

    Syntax:

    var myVariable = value
    
    switch myVariable {
        case condition1:
            expression1
            fallthrough // Optional
        case condition2:
            expression2
            fallthrough // Optional
        ...
        default: // Optional if the switch is exhaustive
            expression
    }
    Why Use Switch Statements?

    Switch statements provide a cleaner and more readable alternative to multiple if-else statements. They are especially useful when evaluating a variable against multiple cases.

    Example 1: Basic Switch Statement

    // Example: Print a string based on a character
    
    var myCharacter = "B"
    
    switch myCharacter {
    case "A":
        print("Apple")
    case "B":
        print("Boy")
    case "C":
        print("Cat")
    case "D":
        print("Dog")
    default:
        print("Invalid")
    }

    Output:

    Boy
    Fallthrough Statement

    The fallthrough keyword forces the execution to proceed to the next case, regardless of whether its condition matches.

    Example: Using Fallthrough

    var myCharacter = "B"
    
    switch myCharacter {
    case "A":
        print("Apple")
    case "B":
        print("Boy")
        fallthrough
    case "C":
        print("Cat")
    case "D":
        print("Dog")
    default:
        print("Invalid")
    }

    Output:

    Boy
    Cat
    No Implicit Fallthrough

    Unlike other languages like C, Swift doesn’t allow implicit fallthrough between cases. Each case must contain an executable body, or the compiler will raise an error.

    Example:

    var myCharacter = "B"
    
    switch myCharacter {
    case "A":
        print("Apple")
    case "B":
        // Missing body
    case "C":
        print("Cat")
    case "D":
        print("Dog")
    default:
        print("Invalid")
    }

    Error:

    'case' label in a 'switch' should have at least one executable statement
    Interval Matching

    Swift enables interval-based matching within case conditions.

    Example:

    var myInteger = 18
    
    switch myInteger {
    case 2:
        print("Equal to 2")
    case 3..<5:
        print("Between 3 and 5")
    case 6..<10:
        print("Between 6 and 10")
    case 11..<22:
        print("Between 11 and 22")
    default:
        print("Invalid")
    }

    Output:

    Between 11 and 22
    Tuple Matching

    Switch statements can evaluate tuples to test multiple values simultaneously. An underscore (_) serves as a wildcard.

    Example:

    var myTuple = (4, 10)
    
    switch myTuple {
    case (2, 3):
        print("First case gets executed")
    case (1...3, 5...11):
        print("Second case gets executed")
    case (1...5, 8...13):
        print("Third case gets executed")
    case (11...13, 15...18):
        print("Fourth case gets executed")
    default:
        print("Invalid")
    }

    Output:

    Third case gets executed
    Value Binding

    Switch statements allow temporary variables to be declared in case conditions. These variables are accessible only within their respective case blocks.

    Example:

    var myTuple = (2, 4, 6)
    
    switch myTuple {
    case (let myElement1, 3, 6):
        print("myElement1 is \(myElement1)")
    case (let myElement1, let myElement2, 6):
        print("myElement1 is \(myElement1), myElement2 is \(myElement2)")
    case (let myElement1, let myElement2, let myElement3):
        print("myElement1 is \(myElement1), myElement2 is \(myElement2), myElement3 is \(myElement3)")
    }

    Output:

    myElement1 is 2, myElement2 is 4
    Using where Clause in a Switch Statement

    The where clause adds additional conditions to a case.

    Example:

    var myTuple = (20, 10)
    
    switch myTuple {
    case let (myElement1, myElement2) where myElement1 == 3 * myElement2:
        print("myElement1 is thrice of myElement2")
    case let (myElement1, myElement2) where myElement1 == 2 * myElement2:
        print("myElement1 is twice of myElement2")
    case let (myElement1, myElement2) where myElement1 == myElement2:
        print("myElement1 is equal to myElement2")
    default:
        print("Invalid")
    }

    Output:

    myElement1 is twice of myElement2
    Compound Cases

    Swift allows multiple conditions to share a single case body by separating them with commas.

    Example:

    var myCharacter = "B"
    
    switch myCharacter {
    case "A", "B":
        print("Either Apple or Boy")
    case "C":
        print("Cat")
    case "D":
        print("Dog")
    default:
        print("Invalid")
    }

    Output:

    Either Apple or Boy

    Loops

    In general, loops are used for iteration, which means repeating a set of instructions. With loops, we can execute tasks multiple times, as required. A loop can run indefinitely until its specified condition is no longer satisfied. Typically, we define a condition to terminate the loop. For instance, if we want to display “Hello World” 100 times, we use a loop and specify a condition such as n <= 100. The loop will terminate when the condition is no longer met.

    Types of Loops in Swift

    1. for-in loop
    2. while loop
    3. repeat-while loop

    1. for-in Loop: The for-in loop is used for iterating over a sequence, such as arrays, dictionaries, ranges, or sets. Unlike an if statement, which executes a block of code only once if a condition is met, the for-in loop repeatedly executes the block as long as the condition is satisfied.

    Syntax:

    for item in range {
        // Statements
    }

    Example:

    // Swift program to find if a number is a perfect number
    
    // Declaring variables
    var number = 6
    var sum = 0
    
    // Iterating to find divisors of the number
    for i in 1...(number - 1) {
        if number % i == 0 {
            sum += i
        }
    }
    
    // Checking if the sum equals the number
    if sum == number {
        print("The given number is a perfect number")
    } else {
        print("The given number is not a perfect number")
    }

    Output:

    The given number is a perfect number

    2. While Loopwhile loop repeatedly executes a block of code as long as the specified condition evaluates to true. Unlike the for-in loop, the while loop requires explicit initialization, condition checking, and variable updates.

    Syntax:

    while condition {
        // Statements
        increment/decrement
    }

    Example:

    // Swift program to calculate the factorial of a number
    
    // Declaring variables
    var num = 5
    var factorial = 1
    var i = 1
    
    // Iterating to calculate factorial
    while i <= num {
        factorial *= i
        i += 1
    }
    
    print("The factorial of the given number is \(factorial)")

    Output:

    The factorial of the given number is 120

    3. Repeat-While Loop: The repeat-while loop, similar to the do-while loop in C, executes the block of code at least once before evaluating the condition. It is also referred to as an exit-controlled loop.

    Syntax:

    repeat {
        // Statements
    } while condition

    Example:

    // Swift program to demonstrate repeat-while loop
    
    // Declaring variables
    var start = 1
    let limit = 10
    
    // Iterating using repeat-while loop
    repeat {
        print(start)
        start += 1
    } while start <= limit

    Output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    Break Statement

    The break statement is a control statement used to immediately terminate the execution of the current loop or switch statement. When the break condition is met, the loop stops its iterations, and control passes to the first statement following the loop. In simpler terms, the break statement halts the current program flow based on specified conditions. It can be used within loops or switch statements to terminate execution earlier, especially when the number of iterations isn’t predetermined or depends on dynamic conditions.

    Syntax:

    break

    1. for-in Loop: The for-in loop in Swift iterates over a sequence, such as a range, array, or string. The break statement can terminate the loop when a specific condition is satisfied.

    Syntax:

    for item in sequence {
        // Code block
        if condition {
            break
        }
    }

    Example:

    // Swift program demonstrating the use of break in a for-in loop
    
    print("Numbers in the range:")
    
    // Loop from 1 to 10
    for number in 1...10 {
        if number == 7 {
            break
        }
        print(number)
    }

    Output:

    Numbers in the range:
    1
    2
    3
    4
    5
    6

    2. While Loop: The while loop runs as long as the given condition is true. The break statement can be used to terminate the loop based on an additional condition.

    Syntax:

    while condition {
        // Code block
        if condition {
            break
        }
    }

    Example:

    // Swift program demonstrating the use of break in a while loop
    
    var count = 1
    
    // Loop to print the first 4 multiples of 3
    while count <= 10 {
        print("3 x \(count) = \(3 * count)")
        if count == 4 {
            break
        }
        count += 1
    }

    Output:

    3 x 1 = 3
    3 x 2 = 6
    3 x 3 = 9
    3 x 4 = 12

    3. Nested Loops: The break statement can also be used in nested loops to terminate only the inner loop or control the flow of nested structures.

    Syntax:

    for item1 in sequence1 {
        for item2 in sequence2 {
            if condition {
                break
            }
        }
    }

    Example:

    // Swift program demonstrating break in nested loops
    
    for outer in 1...3 {
        for inner in 1...3 {
            if outer == 2 {
                break
            }
            print("Outer: \(outer), Inner: \(inner)")
        }
    }

    Output:

    Outer: 1, Inner: 1
    Outer: 1, Inner: 2
    Outer: 1, Inner: 3
    Outer: 3, Inner: 1
    Outer: 3, Inner: 2
    Outer: 3, Inner: 3