Author: Pooja Kotwani

  • 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
  • Swift Control Flow

    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
  • Swift Data Types

    In any programming language, data types are crucial for determining the type of data stored in a variable. In Swift, variables are used to store data, and their type determines what kind of data they hold. This helps the operating system allocate appropriate memory and ensures that only the correct type of data is stored. For instance, an integer variable can only hold integer values, not strings. Swift supports the following primary data types:
    Int, String, Float, Double, Bool, and Character.

    Integer and Floating-Point Numbers

    Integers are whole numbers that can be positive, negative, or zero. They do not contain fractional components. In programming, integers are classified as:

    • Unsigned integers (UInt): Zero or positive numbers.
    • Signed integers (Int): Can include negative numbers.

    Swift provides integers in various bit sizes: 8-bit, 16-bit, 32-bit, and 64-bit. The naming convention follows a pattern similar to C. For example:

    • A signed 16-bit integer is represented as Int16.
    • An unsigned 8-bit integer is represented as UInt8.
    Integer Bounds

    The following table shows the minimum and maximum values for each integer type:

    Integer TypeMinMax
    UInt80255
    UInt16065,535
    UInt3204,294,967,295
    UInt64018,446,744,073,709,551,615
    Int8-128127
    Int16-32,76832,767
    Int32-2,147,483,6482,147,483,647
    Int64-9,223,372,036,854,775,8089,223,372,036,854,775,807

    Swift also provides two additional types:

    • Int: Platform-native integer, equivalent to Int32 on 32-bit platforms and Int64 on 64-bit platforms.
    • UInt: Platform-native unsigned integer, similar to UInt32 or UInt64 depending on the platform.
    Finding Minimum and Maximum Values

    Swift allows us to find the bounds of integer types using the .min and .max properties. Here’s an example:

    Example:

    print("Integer Type        Min                    Max")
    print("UInt8           \(UInt8.min)         \(UInt8.max)")
    print("UInt16          \(UInt16.min)        \(UInt16.max)")
    print("UInt32          \(UInt32.min)        \(UInt32.max)")
    print("UInt64          \(UInt64.min)        \(UInt64.max)")
    print("Int8            \(Int8.min)          \(Int8.max)")
    print("Int16           \(Int16.min)         \(Int16.max)")
    print("Int32           \(Int32.min)         \(Int32.max)")
    print("Int64           \(Int64.min)         \(Int64.max)")

    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
    Floating-Point Numbers

    Floating-point numbers can represent both integers and numbers with fractional components. Swift provides two types of floating-point numbers:

    TypeBit SizeDecimal Precision
    Double64-bitUp to 15 decimal places
    Float32-bitUp to 6 decimal places

    These numbers can represent values like: 5.670.012345.6789, etc.

    Examples

    // Using Double
    var largeDecimal: Double = 12345.6789012345
    print("Double value is:", largeDecimal)
    
    // Using Float
    var smallDecimal: Float = 5.6789
    print("Float value is:", smallDecimal)

    Output:

    Double value is: 12345.6789012345
    Float value is: 5.6789

    Strings in Swift

    Strings in Swift are collections of characters. For example, "Hello, World!" is a string. Swift strings are Unicode-compliant and case-insensitive. They are encoded using UTF-8, which defines how Unicode data is stored in bytes.

    In Swift, strings are a fundamental data type and are often implemented as an array of characters. They can also represent more general collections or sequences of data elements.

    Creating a String

    Strings in Swift can be created using string literals, the String keyword, or the String initializer.

    Syntax:

    var str: String = "Hello, Swift!"
    var str2 = "Swift Programming"

    Examples:

    // String creation using string literal
    var greeting = "Welcome to Swift Programming"
    print(greeting)
    
    // String creation using String instance
    var message = String("This is an example")
    print(message)
    
    // String creation using String keyword
    var note: String = "Enjoy Coding"
    print(note)

    Output:

    Welcome to Swift Programming
    This is an example
    Enjoy Coding
    Multi-Line String

    A multi-line string spans multiple lines and is enclosed in triple double quotes.

    Syntax:

    """
    This is a
    multi-line string
    example in Swift.
    """

    Example:

    let multilineString = """
    Swift strings are versatile.
    You can create multi-line strings
    easily with triple quotes.
    """
    
    print(multilineString)

    Output:

    Swift strings are versatile.
    You can create multi-line strings
    easily with triple quotes.
    Empty String

    An empty string is a string with no characters. You can create an empty string using either "" or the String() initializer.

    Syntax:

    var emptyStr = ""
    var anotherEmptyStr = String()

    Example:

    var empty = ""
    if empty.isEmpty {
        print("The string is empty.")
    }
    
    let anotherEmpty = String()
    if anotherEmpty.isEmpty {
        print("This is also an empty string.")
    }

    Output:

    The string is empty.
    This is also an empty string.
    String Concatenation

    Strings can be concatenated using various methods:

    1. Addition Operator (+):

    var result = str1 + str2

    2. Addition Assignment Operator (+=):

    result += str2

    3. Append Method:

    str1.append(str2)

    Example:

    let part1 = "Swift "
    let part2 = "is powerful."
    
    // Using +
    var sentence = part1 + part2
    print(sentence)
    
    // Using +=
    var phrase = "Learning "
    phrase += "Swift is fun."
    print(phrase)
    
    // Using append()
    var text = "Hello"
    text.append(", Swift!")
    print(text)

    Output:

    Swift is powerful.
    Learning Swift is fun.
    Hello, Swift!
    String Comparison

    Strings can be compared using the == (equal to) or != (not equal to) operators.

    Syntax:

    string1 == string2
    string1 != string2

    Example:

    let stringA = "Swift Programming"
    let stringB = "Learning Swift"
    
    if stringA == stringB {
        print("The strings are equal.")
    } else {
        print("The strings are not equal.")
    }

    Output:

    The strings are not equal.
    String Length

    The length of a string can be determined using the count property.

    Example:

    let text = "Swift Language"
    print("The length of '\(text)' is \(text.count).")

    Output:

    The length of 'Swift Language' is 14.
    String Interpolation

    String interpolation allows mixing variables, constants, and expressions into a string.

    Syntax:

    let str = "Swift \(version)"

    Example:

    let value = 42
    let multiplier = 2
    print("The result of \(value) times \(multiplier) is \(value * multiplier).")

    Output:

    The result of 42 times 2 is 84.
    String Iteration

    Strings can be iterated over using a for-in loop.

    Example:

    for char in "Swift" {
        print(char, terminator: " ")
    }

    Output:

    S w i f t
    Common String Functions and Properties
    NameDescription
    isEmptyChecks if the string is empty.
    hasPrefixChecks if the string starts with the specified prefix.
    hasSuffixChecks if the string ends with the specified suffix.
    countReturns the length of the string.
    utf8Returns the UTF-8 representation of the string.
    insert(_:at:)Inserts a value at a specified position.
    remove(at:)Removes a value at a specified position.
    reversed()Returns the reversed string.

    Example:

    let sample = "Swift Language"
    
    // Using isEmpty
    print("Is string empty? \(sample.isEmpty)")
    
    // Using hasPrefix
    print("Does string start with 'Swift'? \(sample.hasPrefix("Swift"))")
    
    // Using reversed()
    print("Reversed string: \(String(sample.reversed()))")

    Output:

    Is string empty? false
    Does string start with 'Swift'? true
    Reversed string: egaugnaL tfiwS

    String Functions and Operators in Swift

    A string is a sequence of characters that can either be a literal constant or a variable. For example, "Hello World" is a string of characters. Swift strings are Unicode-correct and locale-insensitive. They support various operations like comparison, concatenation, iteration, and more.

    Creating Strings in Swift

    You can create strings in Swift using either a String instance or a string literal.

    1. Using String() Initializer: The String() initializer creates a string instance.

    Syntax:

    var str = String("Example String")

    Example:

    // Using String() initializer
    var greeting = String("Welcome to Swift!")
    print(greeting)

    Output:

    Welcome to Swift!

    2. Using String Literal: Double quotes are used to create string literals, similar to other programming languages.

    Syntax:

    var str = "Hello"
    var strTyped: String = "World"

    Examples:

    // Creating strings using literals
    var message = "Learning Swift is fun!"
    print(message)
    
    var typedMessage: String = "Swift Programming"
    print(typedMessage)

    Output:

    Learning Swift is fun!
    Swift Programming
    Multi-line Strings 

    Swift supports multi-line strings using triple double quotes (""").

    Syntax:

    Learning Swift is fun!
    Swift Programming

    Examples:

    // Multi-line string example
    let paragraph = """
    Welcome to Swift!
    This example demonstrates
    multi-line strings.
    """
    print(paragraph)

    Output:

    Welcome to Swift!
    This example demonstrates
    multi-line strings.
    String Properties and Functions

    Empty String: An empty string has no characters and a length of zero.

    Example:

    // Creating an empty string
    var emptyLiteral = ""
    var emptyInstance = String()
    
    print("Is emptyLiteral empty? \(emptyLiteral.isEmpty)")
    print("Is emptyInstance empty? \(emptyInstance.isEmpty)")

    Output:

    Is emptyLiteral empty? true
    Is emptyInstance empty? true

    String Length: The count property returns the total number of characters in a string.

    Example:

    // Counting characters in a string
    let text = "Swift Programming"
    let length = text.count
    print("The length of the text is \(length)")

    Output:

    The length of the text is 18
    String Operations

    1. Concatenation: The + operator concatenates strings.

    Example:

    // Concatenating strings
    let firstName = "John"
    let lastName = "Doe"
    let fullName = firstName + " " + lastName
    print("Full Name: \(fullName)")

    Output:

    Full Name: John Doe

    2. Comparison: Use == to check equality and != to check inequality.

    Example:

    let a = "Swift"
    let b = "Swift"
    let c = "Python"
    
    // Equality
    print(a == b)  // true
    
    // Inequality
    print(a != c)  // true

    Output:

    true
    true
    String Functions:

    1. hasPrefix and hasSuffix: Check if a string starts or ends with a specific substring.

    Example:

    let sentence = "Learning Swift"
    print(sentence.hasPrefix("Learn"))  // true
    print(sentence.hasSuffix("Swift")) // true

    Output:

    true
    true

    2. lowercased() and uppercased(): Convert all characters in a string to lowercase or uppercase.

    Example:

    let text = "Swift Programming"
    print(text.lowercased())  // "swift programming"
    print(text.uppercased())  // "SWIFT PROGRAMMING"

    Output:

    swift programming
    SWIFT PROGRAMMING

    3. reversed(): Reverse the characters of a string.

    Example:

    let word = "Swift"
    let reversedWord = String(word.reversed())
    print("Original: \(word)")
    print("Reversed: \(reversedWord)")

    Output:

    Original: Swift
    Reversed: tfiwS

    4. insert(_:at:): Insert a character at a specified position.

    Example:

    var phrase = "Swift Programming"
    phrase.insert("!", at: phrase.endIndex)
    print(phrase)

    Output:

    Swift Programming!

    5. remove(at:): Remove a character at a specific index.

    Example:

    var text = "Hello Swift!"
    let index = text.index(text.startIndex, offsetBy: 6)
    let removedCharacter = text.remove(at: index)
    print("Modified text: \(text)")
    print("Removed character: \(removedCharacter)")

    Output:

    Modified text: Hello Sift!
    Removed character: w

    Data Type Conversions in Swift

    Type Conversion in Swift

    Type Conversion refers to the process of converting a variable or value from one data type to another. This allows instances to be checked and cast to specific class types. In Swift, type conversion is often performed during compile-time by the XCode compiler, provided the data types are compatible (e.g., integer, string, float, double).

    Type conversion involves explicitly casting a value to a different data type using the desired type as a function. For instance:

    var stringToFloatNum: Float = Float(67891)!

    Syntax:

    var <variable_name>: <data_type> = <convert_data_type>(<value>)

    1. Convert Integer to String: This program converts an integer value to a string and displays the result with its type.

    Example:

    import Swift
    
    var intNumber: Int = 789
    
    var intNumberToString: String = String(intNumber)
    
    print("Integer Value = \(intNumber) of type \(type(of: intNumber))")
    print("String Value = \(intNumberToString) of type \(type(of: intNumberToString))")

    Output:

    Integer Value = 789 of type Int
    String Value = 789 of type String

    2. Convert String to Integer: This program converts a string value to an integer and displays the result with its type.

    Example:

    import Swift
    
    var intNum: Int = 789
    
    var intNumToFloat: Float = Float(intNum)
    
    print("Integer Value = \(intNum) of type \(type(of: intNum))")
    print("Float Value = \(intNumToFloat) of type \(type(of: intNumToFloat))")

    Output:

    String Value = 789 of type String
    Integer Value = 789 of type Int

    3. Convert String to Integer: This program converts a string value to an integer and displays the result with its type.

    Example:

    import Swift
    
    var string: String = "789"
    
    var stringToInt: Int = Int(string)!
    
    print("String Value = \(string) of type \(type(of: string))")
    print("Integer Value = \(stringToInt) of type \(type(of: stringToInt))")

    Output:

    String Value = 789 of type String
    Integer Value = 789 of type Int

    4. Convert Integer to Float: This program converts an integer value to a float and displays the result with its type.

    Example:

    import Swift
    
    var intNum: Int = 789
    
    var intNumToFloat: Float = Float(intNum)
    
    print("Integer Value = \(intNum) of type \(type(of: intNum))")
    print("Float Value = \(intNumToFloat) of type \(type(of: intNumToFloat))")

    Output:

    Integer Value = 789 of type Int
    Float Value = 789.0 of type Float

    5. Convert Float to Integer: This program converts a float value to an integer and displays the result with its type.

    Example:

    import Swift
    
    var floatNum: Float = 789.0089
    
    var floatNumToInt: Int = Int(floatNum)
    
    print("Float Value = \(floatNum) of type \(type(of: floatNum))")
    print("Integer Value = \(floatNumToInt) of type \(type(of: floatNumToInt))")

    Output:

    Float Value = 789.0089 of type Float
    Integer Value = 789 of type Int

    6. Convert String to Float: This program converts a string value to a float and displays the result with its type.

    Example:

    import Swift
    
    var string: String = "789"
    
    var stringToFloatNum: Float = Float(string)!
    
    print("String Value = \(string) of type \(type(of: string))")
    print("Float Value = \(stringToFloatNum) of type \(type(of: stringToFloatNum))")

    Output:

    String Value = 789 of type String
    Float Value = 789.0 of type Float

    Convert String to Int Swift

    In Swift, you can convert a string into an integer using various methods. However, only numeric strings can be successfully converted to integers. Below are two common methods to perform this conversion.

    Declaring a String Variable

    A string in Swift is a collection of characters and can be declared using the String data type.

    Syntax:

    let myVariable: String

    Example:

    let myVariable = "Hello"
    Methods for String to Integer Conversion

    1. Using Int Initializer Swift provides an initializer function for integers that can convert a string to an Int. This initializer returns an optional integer. To handle non-numeric strings, you can use the nil-coalescing operator to provide a default value, such as 0.

    Example:

    // Converting a numeric string
    let myStringVariable = "25"
    let myIntegerVariable = Int(myStringVariable) ?? 0
    print("Integer Value:", myIntegerVariable)
    
    // Converting a non-numeric string
    let myStringVariable2 = "Hello"
    let myIntegerVariable2 = Int(myStringVariable2) ?? 0
    print("Integer Value:", myIntegerVariable2)

    Output:

    Integer Value: 25
    Integer Value: 0

    2. Using NSString:The NSString class in Swift allows strings to be passed by reference and includes the integerValue property, which can be used to convert an NSString to an integer.

    Example:

    import Foundation
    
    let myString = "25"
    
    // Converting a string to NSString and then to an integer using integerValue
    let myIntegerVariable = (myString as NSString).integerValue
    print("Integer Value:", myIntegerVariable)

    Output:

    Integer Value: 25
  • Swift Overview

    Swift is a powerful and intuitive programming language developed by Apple Inc. for iOS, macOS, watchOS, and tvOS app development. It was first released in 2014 and has quickly gained popularity due to its simplicity, safety, and performance.

    Key Features
    • Open Source: Swift is open-source, allowing developers to contribute and use it on a wide range of platforms.
    • Safety: Swift is designed with safety in mind, with features like optionals that help prevent null pointer errors.
    • Performance: Swift is optimized for performance, often outperforming Objective-C in various tasks.
    • Modern Syntax: Swift’s syntax is clean and concise, making it easier to read and write.

    Swift Basic Syntax

    Swift’s syntax is designed to be concise and expressive. Below are some basic syntax elements of Swift:

    Hello, World! Example

    Here’s a simple “Hello, World!” program in Swift:

    print("Hello, World!")

    Identifiers

    Identifiers are names used to identify variables, functions, or other user-defined items. They must begin with an alphabet (A-Z or a-z) or an underscore (_) and may contain letters, underscores, and digits. Swift is case-sensitive, so A and a are treated as distinct. Special characters like @#, and % are not allowed in identifiers.

    Examples:

    a, _temp, Temp, a_bc, a29b, temp12, temp_11

    To use a reserved word as an identifier, enclose it in backticks (`).
    Example:

    `exampleIdentifier`

    Keywords

    Keywords are reserved words with predefined meanings in Swift. They cannot be used as variable names or identifiers.

    Examples of Keywords:

    class, func, let, public, struct, return, for, while, if, else, true, false

    Every programming language has a set of reserved words used for internal processes or predefined actions. These reserved words, known as keywords, cannot be used as variable names, constant names, or other identifiers. To use a keyword as an identifier, enclose it in backticks (). For instance, while structis a keyword, “struct“ is a valid identifier. Note that backticks do not change the case sensitivity of identifiers (e.g.,aanda` are treated the same).

    In Swift, keywords are categorized into the following groups:

    1. Keywords in declaration
    2. Keywords in statements
    3. Keywords in expressions and types
    4. Keywords in specific contexts
    5. Keywords starting with the number sign (#)
    6. Keywords used in patterns (_)

    1. Keywords Used in Declarations: Keywords used in declarations include:

    associatedtype, class, deinit, enum, extension, fileprivate, func, import,
    init, inout, internal, let, open, operator, private, precedencegroup,
    protocol, public, rethrows, static, struct, subscript, typealias, var

    Example:

    import Swift
    
    // Creating a structure using the `struct` keyword
    struct Employee {
        var name = "John"
        var id = 1234
    }
    
    // Creating an instance of the structure
    var instance = Employee()
    
    // Accessing properties of the structure
    print("Employee Name:", instance.name)
    print("Employee ID:", instance.id)

    Output:

    Employee Name: John
    Employee ID: 1234

    2. Keywords Used in Statements: Keywords used in statements include:

    break, case, catch, continue, default, defer, do, else, fallthrough, for,
    guard, if, in, repeat, return, throw, switch, where, while

    Example:

    import Swift
    
    // Finding the age group
    let age = 70
    
    if age >= 60 {
        print("Senior Citizen")
    } else if age >= 40 {
        print("Middle-aged")
    } else {
        print("Young")
    }

    Output:

    Senior Citizen

    3. Keywords Used in Expressions and Types: Keywords in expressions and types include:

    Any, as, catch, false, is, nil, rethrows, self, Self, super, throw, throws,
    true, try

    Example:

    import Swift
    
    // Creating a class
    class Person {
        func name() {
            print("Hello! My name is Alice")
        }
    }
    
    // Creating a subclass
    class Employee: Person {
        override func name() {
            // Accessing the parent class method using `super`
            super.name()
            print("I work in the IT department")
        }
    }
    
    // Creating an instance of the subclass
    let employee = Employee()
    employee.name()

    Output:

    Hello! My name is Alice
    I work in the IT department

    4. Keywords Used in Specific Contexts: Keywords used in specific contexts include:

    associativity, convenience, didSet, dynamic, final, get, indirect, infix,
    lazy, left, mutating, none, nonmutating, optional, override, postfix,
    precedence, prefix, Protocol, required, right, set, some, Type, unowned,
    weak, willSet

    Example:

    import Swift
    
    // Creating a structure
    struct Data {
        var value: String
    
        // Using the `mutating` keyword
        mutating func updateValue() {
            self.value = "Updated Value"
        }
    }
    
    var data = Data(value: "Initial Value")
    data.updateValue()
    print(data.value)

    Output:

    Updated Value

    5. Keywords Starting with the Number Sign (#): Keywords starting with # include:

    #available, #colorLiteral, #column, #dsohandle, #elseif, #else, #endif,
    #error, #fileID, #fileLiteral, #filePath, #file, #function, #if,
    #imageLiteral, #keyPath, #line, #selector, #sourceLocation, #warning

    Example:

    import Swift
    
    // Using `#function` to display the function name
    func displayFunctionName() {
        print("You are in the function: \(#function)")
    }
    
    displayFunctionName()

    Output:

    You are in the function: displayFunctionName

    6. Keywords Used in Patterns (_): The underscore (_) is used as a wildcard in patterns.

    Example:

    import Swift
    
    // Printing a message 10 times
    for _ in 1...10 {
        print("Swift Programming")
    }

    Output:

    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming
    Swift Programming

    Semicolons (;)

    Semicolons are optional in Swift but are required when writing multiple statements on the same line.

    Examples:

    var a = 1; var b = 2
    print(a); print(b)

    Output:

    1
    2

    Whitespaces

    Whitespace separates elements in code and improves readability. It is mandatory between keywords and identifiers but optional elsewhere.

    Examples:

    var a = 1
    var b=2 // Valid but less readable
    var c = a + b // Preferred for readability

    Literals

    Literals represent fixed values in a program, such as integers, decimals, strings, or booleans. These values can be directly used without computation. By default, literals in Swift don’t have a type. Primitive type variables can be assigned literals. For instance:

    • 12 is an integer literal.
    • 3.123 is a floating-point literal.
    • “Swift” is a string literal.
    • true is a boolean literal.
    Swift Protocols for Literals

    Literals must conform to specific protocols depending on their type:

    • ExpressibleByIntegerLiteral: For integer literals.
    • ExpressibleByFloatLiteral: For floating-point literals.
    • ExpressibleByStringLiteral: For string literals.
    • ExpressibleByBooleanLiteral: For boolean literals.

    Example:

    let number: Int32 = 25
    Types of Literals in Swift

    1. Integer Literals: Used to represent whole numbers. If no alternate base is specified, they default to base-10 (decimal). Negative integers are represented using a minus sign (-).

    Examples:

    let positiveNumber = 25
    let negativeNumber = -25
    let numberWithUnderscore = 2_500 // Same as 2500

    Alternate Representations:

    • Binary: Prefix with 0b
    • Octal: Prefix with 0o
    • Hexadecimal: Prefix with 0x

    Example

    let decimalNumber = 10
    let binaryNumber = 0b1010
    let octalNumber = 0o12
    let hexadecimalNumber = 0xA
    
    print("Decimal Number:", decimalNumber)
    print("Binary Number:", binaryNumber)
    print("Octal Number:", octalNumber)
    print("Hexadecimal Number:", hexadecimalNumber)

    Comments make code more understandable. They are ignored by the compiler.

    Single-line comment syntax:

    Decimal Number: 10
    Binary Number: 10
    Octal Number: 10
    Hexadecimal Number: 10

    2. Floating-Point Literals: Represent numbers with a decimal point. The default type is Double. You can explicitly specify the type as Float.

    Examples:

    let number: Int32 = 25

    Exponential Representation:

    let scientificNumber1 = 1.25e3 // 1250
    let scientificNumber2 = 1.25e-3 // 0.00125

    Hexadecimal Floating-Point:

    • Prefix: 0x
    • Exponent: p
    let hexFloat1 = 0xFp1 // 30.0
    let hexFloat2 = 0xFp-1 // 7.5

    Example:

    let decimalFloatingNumber = 0.123
    let scientificNotation = 1.23e2
    let hexFloat = 0xFp1
    
    print("Decimal Floating-Point:", decimalFloatingNumber)
    print("Scientific Notation:", scientificNotation)
    print("Hexadecimal Floating-Point:", hexFloat)

    Output:

    \Decimal Floating-Point: 0.123
    Scientific Notation: 123.0
    Hexadecimal Floating-Point: 30.0

    3. String Literals: Represent a sequence of characters enclosed in double quotes. Strings can be multi-line, escape special characters, or use interpolation.

    • Single-Line String:
    let message = "Hello, World!"
    • Multi-Line String:
    vlet multilineString = """
    This is a
    multi-line string.
    """
    • Escape Sequences:
    let escapedString = "Hello,\nWorld!"
    • String Interpolation:
    let name = "Swift"
    let greeting = "Welcome to \(name) programming!"

    Example:

    let singleLine = "Learning Swift"
    let multiLine = """
    Multi-line
    String Example
    """
    let interpolated = "The value is \(42)"
    
    print(singleLine)
    print(multiLine)
    print(interpolated)

    Output:

    Learning Swift
    Multi-line
    String Example
    The value is 42

    4. Boolean Literals: Boolean literals can be true or false. The default type is Bool.

    Examples:

    let value1 = true
    let value2 = false
    
    print("Value 1:", value1)
    print("Value 2:", value2)

    Output:

    Value 1: true
    Value 2: false

    Comments

    Comments make code more understandable. They are ignored by the compiler.

    Single-line comment syntax:

    // This is a single-line comment

    Multi-line comment syntax:

    /*
    This is a
    multi-line comment
    */

    Print Statement

    The print function displays text, variables, or expressions on the screen.

    Examples:

    print("Hello Swift") // Prints: Hello Swift
    
    var x = 10
    print(x) // Prints: 10
    
    print(5 + 3) // Prints: 8

    Output:

    Hello Swift
    10
    8

    Import Class

    The import keyword brings definitions from another module into the current program.

    Syntax:

    import module

    Examples:

    import Swift
    print("Welcome to Swift Programming")

    Output:

    Welcome to Swift Programming

    Variables and Constants

    Constants and variables in Swift are used to store data with specific types, such as numbers, characters, or strings. A constant cannot be changed after it has been assigned a value, whereas a variable can be modified during the program execution.

    Declaring Constants & Variables in Swift

    Constants and variables must be declared within their scope before being used. The let keyword is used for constants, and the var keyword is used for variables. Swift does not require semicolons (;) to terminate statements.

    let temperature = 20 // Declaring a constant
    var count = 0        // Declaring a variable

    You can declare multiple constants or variables in a single line, separated by commas:

    let x = 10, y = 20, z = 30 // Multiple constants
    var p = 1, q = 2, r = 3    // Multiple variables
    Type Annotation

    Type annotation explicitly specifies the type of a constant or variable at the time of declaration. For example:

    var name: String // Declares a string variable without initialization
    var age: Int     // Declares an integer variable

    If multiple constants or variables are of the same type, you can declare them in one line:

    var firstName, lastName, city: String
    Naming Constants & Variables

    Names can contain any character except mathematical symbols, private Unicode scalar values, arrows, or whitespace characters:

    let pi = 3.14159
    print("Value of pi: \(pi)")
    Printing Constants & Variables

    print() Function

    The print(_:separator:terminator:) function is used to display the value of constants or variables.

    Example:

    let country = "India"
    print(country)

    Output:

    India

    String Interpolation: String interpolation allows embedding constants or variables directly within a string, replacing placeholders with actual values.

    Example:

    var city = "Delhi"
    print("I live in \(city)")

    Output:

    I live in Delhi
  • Swift Tutorial Roadmap

    Introduction to Swift

    Overview of Swift

    Swift is a powerful, modern, and safe programming language developed by Apple for building applications on iOS, macOS, watchOS, and tvOS. It is designed to be fast, expressive, and beginner-friendly while offering high performance for production apps.


    Swift Basic Syntax

    Identifiers and Keywords

    • Swift identifiers and naming conventions
    • Reserved keywords and their usage

    Semicolons and Whitespaces

    • Use of semicolons (;) in Swift
    • Importance of whitespaces in Swift syntax

    Literals

    • Integer literals
    • Floating-point literals
    • String literals
    • Boolean literals

    Comments

    • Single-line comments
    • Multi-line comments

    Print Statement

    • Using print() to display output

    Import Statements

    • Importing frameworks and modules

    Variables and Constants

    Declaring Variables and Constants

    • Using var for variables
    • Using let for constants

    Data Types

    • Type inference in Swift
    • Explicit type annotations

    Numeric Types

    • Integers
    • Floating-point numbers

    Strings in Swift

    String Basics

    • Creating and initializing strings

    String Functions

    • Common string manipulation methods

    Operators in Swift

    Types of Operators

    • Arithmetic operators
    • Comparison operators
    • Logical operators
    • Assignment operators

    Data Type Conversions in Swift

    Type Conversion

    • Converting between different data types

    String to Int Conversion

    • Safely converting String to Int

    Control Flow

    Decision-Making Statements

    • if statement
    • if-else statement
    • if-else-if ladder
    • Nested if-else
    • switch statement

    Loops

    Looping Statements

    • for-in loop
    • while loop
    • repeat-while loop

    Break Statement

    • Using break to exit loops

    Swift Functions

    Functions Overview

    • Defining and calling functions

    Parameters and Return Values

    • Function parameters
    • Returning values from functions

    In-Out Parameters

    • Modifying parameters using inout

    Nested Functions

    • Functions defined inside other functions

    Function Overloading

    • Multiple functions with the same name

    Closures in Swift

    Closures Overview

    • Introduction to closures and their syntax

    Escaping and Non-Escaping Closures

    • Understanding closure lifetimes and memory behavior

    Swift Sets

    Introduction to Sets

    • Creating and using sets

    Set Operations

    • Removing the first element
    • Using removeAll()
    • Checking if an element exists
    • Counting elements
    • Sorting a set
    • Checking if a set is empty
    • Shuffling set elements

    Sets vs Arrays

    • Differences and appropriate use cases

    Swift Arrays

    Arrays Overview

    • Creating and initializing arrays

    Array Properties

    • Count and capacity

    Common Array Operations

    • Removing the first element
    • Counting elements
    • Reversing arrays
    • Using joined()
    • Checking if an array contains an element
    • Sorting arrays
    • Swapping elements
    • Checking if an array is empty

    Swift Dictionary

    Dictionary Basics

    • Creating dictionaries
    • Creating empty dictionaries

    Dictionary Operations

    • Changing values
    • Accessing elements
    • Iterating over dictionaries

    Advanced Dictionary Usage

    • Creating a dictionary from two arrays
    • Removing items
    • Converting dictionaries to arrays

    Dictionary Properties

    • Common dictionary properties

    Swift Tuples

    Tuples in Swift

    • Creating and using tuples

    Swift Object-Oriented Programming (OOP)

    Structures in Swift

    • Creating and using structures

    Properties

    • Stored properties
    • Computed properties

    Methods

    • Instance methods
    • Type methods

    Function vs Method

    • Key differences

    Deinitialization

    • Understanding deinitializers

    Typecasting in Swift

    Typecasting

    • Checking types at runtime
    • Upcasting and downcasting

    Timers in Swift

    Repeating Timers

    • Implementing repeating timers

    Non-Repeating Timers

    • Creating one-time timers

    Swift Error Handling

    Errors in Swift

    • Error handling fundamentals

    try, try?, and try!

    • Differences and when to use each

    Additional Swift Topics

    Typealias

    • Creating and using type aliases

    Swift Structures vs C Structures

    • Key differences

    Swift Interview Preparation

    Interview Questions

    • Theoretical questions
    • Advanced coding challenges
    • Scenario-based questions

    Swift Project Ideas

    Project Ideas

    • Beginner-level Swift projects
    • Intermediate and advanced Swift project ideas