Swift Closures

Swift - Closures

Closures are similar to that of self-contained functions organized as blocks and called anywhere like C and Objective C languages. Constants and variable references defined inside the functions are captured and stored in closures. Functions are considered as special cases of closures.

Inferring parameter and return value types from context.Closure expressions in Swift 4 language follow crisp, optimization, and lightweight syntax styles which includes.

  • Implicit returns from single-expression closures.
  • Shorthand argument names and
  • Trailing closure syntax

Syntax

Following is a generic syntax to define closure which accepts parameters and returns a data type −

{
   (parameters) −> return type in
   statements
}

Example:

let studname = { print("Welcome to Swift Closures") }
studname()

Result:

Welcome to Swift Closures

The following closure accepts two parameters and returns a Bool value −

{     
   (Int, Int) −> Bool in
   Statement1
   Statement 2
   ---
   Statement n
}

Example:

let divide = {
   (val1: Int, val2: Int) -> Int in 
   return val1 / val2 
}

let result = divide(200, 20)
print (result)

Result:

10