Swift from Scratch: A Complete Guide (Part 5)

inspirethedev@gmail.com

Defer

Where does Defer work?

Example

func processFile() {
    print("File processing started.")
    
    // Defer block
    defer {
        print("Closing the file.")
    }
    
    print("Processing the file data...")
    // Some file processing logic goes here...
    
    // Returning early, but defer block will still run at the end
    return
}
processFile()

// OUTPUT 
File processing started.
Processing the file data...
Closing the file.

How LIFO Works with defer?

func processTransaction() {
    print("Starting transaction.")
    
    defer {
        print("Transaction rolled back.")
    }
    
    defer {
        print("Logging transaction.")
    }
    
    defer {
        print("Closing database connection.")
    }
    
    print("Processing transaction...")
    // Some transaction processing code here...
}

processTransaction()
// Output
Starting transaction.
Processing transaction...
Closing database connection.
Logging transaction.
Transaction rolled back.

Lazy Properties and Initialization:

class DataManager {
    // Lazy property ka declaration
    lazy var data = loadData()

    // Heavy initialization function
    func loadData() -> [String] {
        print("Data is being loaded...")
        return ["Item1", "Item2", "Item3"]
    }
}

let dataManager = DataManager()
print("DataManager created.")  // Data abhi tak load nahi hua

// Lazy property ko access karte hain
print(dataManager.data)  // Data is being loaded... ["Item1", "Item2", "Item3"]

// OUTPUT 
DataManager created.
Data is being loaded...
["Item1", "Item2", "Item3"]

Subscripts

struct Numbers {
    var values: [Int]
    
    subscript(index: Int) -> Int {
        get {
            return values[index]
        }
        set(newValue) {
            values[index] = newValue
        }
    }
}

var numbers = Numbers(values: [10, 20, 30])
print(numbers[1])  // Output: 20
numbers[2] = 100
print(numbers[2])  // Output: 100

Initalization

Initialization in Swift: Kya Hai?

struct Person {
    var name: String
    var age: Int
    
    // Default initializer
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person = Person(name: "John", age: 30)
print("Name: \(person.name), Age: \(person.age)")  // Output: Name: John, Age: 30

Key Points About Initialization:

let numbers = [1, 2, 3, 4, 5]

// Using filter to get even numbers
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print("Even Numbers: \(evenNumbers)") // Output: [2, 4]

Conclusion

Comments

Leave a Reply

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