Posts

Showing posts with the label Defer

Defer in Swift

Image
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?? YE...