O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Closure syntax

A general closure syntax is as follows:

 { (parameters) -> ReturnType in // body of closure }

A closure definition starts with {, then we define the closure type, and finally we use the in keyword to separate the closure definition from its implementation.

After the in keyword, we write the body of the closure and finish our closure by closing }.

Closures can be used to define variables or stored as variables. The following closure defines a variable of a type closure that accepts Int and returns Int:

let closureName: (Int) -> (Int) = { _ in 10 } 

Closures can be stored as optional variables. The following closure defines a variable of a type closure that accepts Int and returns Optional Int

 var closureName: (Int) -> (Int)? ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required