What is Closure?
A closure is a self-contained block of functionality that can be passed around and used in your code
Tip
Closures are widely used in Swift programming for things like callbacks, completion handlers, and functional programming techniques.
- Closures that can be called after the function they were passed to has returned.
- Declared with
@escaping
.Example Outputvar completionClosure: (() -> Void)? func doSomethingEscaping(closure: @escaping () -> Void) { // This closure is escaping, so we can store it for later execution. completionClosure = closure } func exampleUsage() { doSomethingEscaping { print("This is an escaping closure.") } // At a later point in the code, we can execute the escaping closure. completionClosure?() }
- Closures that do not outlive the function they are passed to.
- They are executed within the function's scope. Example Output
Autoclosures
- It automatically created to wrap an expression that’s being passed as an argument to a function.
- It doesn’t take any arguments.
Example
Output
enum LogLevel: Int {
case debug = 1
case info
case warning
case error
}
var currentLogLevel: LogLevel = .debug
func log(_ level: LogLevel, message: @autoclosure () -> String) {
if level.rawValue >= currentLogLevel.rawValue {
print(message())
}
}
// Logging with different levels
log(.debug, message: "This is a debug message")
log(.info, message: "This is an info message")
log(.warning, message: "This is a warning message")
log(.error, message: "This is an error message")
// Only the message for the current log level or higher will be printed
currentLogLevel = .warning
log(.debug, message: detailedDebugMessage)
log(.info, message: "This info message won't be printed")
log(.warning, message: "This is a warning message")
log(.error, message: "This is an error message")
Let's grow together 🌱
Cheers 🍻