Defer

defer is a statement used to execute a block of code just before the current scope e.g a function or loop exits.

func hello() {
    defer {
        print("Codewithswift")
    }
    print("Hello World")
}

hello()
// Output:
// Hello World
// Codewithswift
 func multipleDefers() {
    defer {
        print("First defer")
    }
    defer {
        print("Second defer")
    }
    defer {
        print("Third defer")
    }
    print("Inside function")
}

multipleDefers()
// Output:
// Inside function
// Third defer
// Second defer
// First defer
func performTaskWithLock() {
    let lock = NSLock()
    lock.lock()
    print("Lock acquired")
    
    defer {
        lock.unlock()
        print("Lock released")
    }
    
    print("Performing task")
}

performTaskWithLock()
// Output:
// Lock acquired
// Performing task
// Lock released

Leave a Reply

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