How Can I Declare a Closure in Swift?

Closures is one type of Self-Contained blocks functionality in which passed value and use that in you code. In objective-c known as Blocks that similar Closures in Swift.

This tutorial provide the declaration of the Closures and how can use the Closure in swift.

Declare Closure as Constant : You can declare constant using Closure.
let myFirstClosure = {
    "Kirit Modi"
calling the closure and get the value of constant.

Declare Closure as Variable : Passing the string value as closure parameter and get the string value. it means you can get variant value from closure.
var closureName = { (myString : String) -> (String) in
    return myString
calling the closure to pass string like "Kirit Modi" and get the variable value also same as passing value.
let myClosure = self.closureName("Kirit Modi")

Declare  Closure as parameter with function : 
Define closure syntax type with typealias. 
typealias closure = (Int , Int) -> ()
Declare function with use of closure syntax.
func myClosureFunction(action: closure) -> () {
calling the closure and get its value inside the function. Here you can get value of A and B inside the block.
self.myClosureFunction { (A, B) in
Declare  Closure function with Return type : Define a function name personalDetails with Closure type (( String , String) -> String).  and return another function inside the Closure that return the value of String. See and understand the full code.
func personalDetails () -> ((String, String) -> String) {

    func fullname(name: String, last: String) -> (String) {
        return name + last
    return fullname
Calling the above function to make one object of personalDetails.
let details = personalDetails()
print(details("Kirit", "Modi"))


How Can I Declare a Closure in Swift? How Can I Declare a Closure in Swift? Reviewed by Kirit Modi on 02:33:00 Rating: 5

No comments:

Powered by Blogger.