Closures are self contained chunks of code that can be passed around and used in your code.

Functions are a special kind of closures. There are three kinds of closures:

  • global functions – they have a name and cannot capture any values
  • nested functions (function inside another function) – they have a name and can capture values from their enclosing functions
  • closure expressions – they don’t have a name and can capture values from their context

The general syntax for declaring closures is:

{ (parameters) -> return type in
 
statements

}

If the closure does not return any value you can omit the arrow (->) and the return type. This also applies to the case where the type of the closure can be inferred.

{ (parameters) in

statements

}

How to write closure :

var noParameterAndNoReturnValue: () -> () = {
    print("Hello!")
}
noParameterAndNoReturnValue   //Hello!

var noParameterAndReturnValue: () -> (Int) = {
    return 1000
}
noParameterAndReturnValue  //1000

var oneParameterAndReturnValue: (Int) -> (Int) = { x in
    return x % 10
}
oneParameterAndReturnValue(99) //9  --we pass parameter to variable because closure has parameter 

var multipleParametersAndReturnValue: (String, String) -> (String) = 
    { (first, second) -> String in
    return first + " " + second
}
multipleParametersAndReturnValue("My","Name") //My Name

above variable  can also written as:

var noParameterAndNoReturnValue = {
    print("Hello!")
}

var noParameterAndReturnValue = {
    return 1000
}

var oneParameterAndReturnValue = { x in
    return x % 10
}

var multipleParametersAndReturnValue = 
    { (first, second) -> String in
    return first + " " + second
}

Shorthand Parameter Names

Swift provides shorthand parameter names for closures. You can refer to the parameters as $0, $1, $2 and so on. To use shorthand parameter names ignore the first part of the declaration.

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –  paypal.me/SandeshSardar

download

Advertisements