Declare a Closure in Swift

Like other data types such as String, Double, Float, Boolean, Array, Dictionary, Struct, and Class, Closure is used broadly in Swift. Closure can store references to any constants and variables.

In this short Swift code example, you will learn how to declare a simple Closure in Swift.

  • Declare a Closure
  • Call Closure

Syntax

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

{ (parameters) −> (return type) in 
   // closure body 
}

Declare a Closure

let simpleClosure = { 
  print("From a simpleClosure") 
}

Call Closure

simpleClosure()

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.