Defer in Swift


  • Defer is another new keyword in Swift. With this statement you can declare clean-up code, that is executed just before the current scope ends.
  • Defer keyword was introduced in Swift 2.0
  • Defer is use to clean up operations like closing any Database connection, freeing up resources, invalidating the login session, etc.

Syntax of Defer

defer {
     statement 1
     statement 2
     .......
}

Example of Defer

func sayHello() {
    defer {
        print("World")
    }
     
    print("Hello")
}
sayHello()
//It will prints "Hello" "World"

Example of Defer with a return type function

class Counter {
  var count = 0

  func returnWithIncrement() -> Int {

    defer {
      count += 1
    }
    print(count)
    return count
  }
}

let counter = Counter()
counter.returnWithIncrement() // Print "0"
counter.returnWithIncrement() // Print "1"


Can we use multiple defer blocks in one function??

YES 😎



Example of multiple defer blocks in one function
func multipleDefer() {
    
    defer {
        print("Third defer")
    }
    
    defer {
        print("Second defer")
    }
    
    defer {
        print("First defer")
    }
}

"First defer"
"Second defer"
"Third defer"


Defer always follows reverse order. It follows the order from bottom to top and so here last defer will always get executed first and following the bottom-up order, the first defer will get executed at the last.

Thanks for reading, Happy Coding ðŸ‘¨‍💻

Popular posts from this blog

Frame vs bounds in Swift

Property wrapper in Swift

DateFomatter in Swift