top
April flash sale

Search

Swift Tutorial

A function is a collection of statements to carry out a particular assignment together. A Swift  function may be as easy as a straightforward C function and as complex as  an Objective C function. This enables us to inside function calls to transfer local and global parameter values. Function declaration: informs the compiler about the name, type of the function, and parameters of the function. Function Definition: The real function body is provided. The "func" keyword is used to define function in Swift . If a function is redefined, one or more values can be added to the function by input parameters, and it processes the functions inside the body , transferring the values back to the functions as return types of output.Each function has a name for the function describing the job performed by this function. In order to use a function, you "call" it by name and pass input values (so-called arguments) that match the parameter types of the function. Also called' tuples ' function parameters. Arguments for a function must always be in the same order as the parameter list for the function and the values for return must always be followed by → Syntax func funcname(Parameters) -> returntype {    Statement1    Statement2    ---    Statement N    return parameters }Check out the code below. The name of the program is declared as a data string in the ‘program’ function, and if the function is called, the name of the student will be returned. func program(name:String)->String{ return name } print(program(name:"Hello")) print(program(name:"World"))In the above example function accepts a parameter of string type and also return type is string. The function is invoked by calling function name (here “program”) with parameter name (“name”) and passing value to the parameter.Swift  offers flexible parameters and returns from simple to complex values. In Swift  functions may take several forms, similar to that of C and Objective C. Let's cover that in detail. Different forms of Swift functions Function with parameterA function is declared by transferring its parameter values to the function body. We can pass single values as tuples in the function to multiple parameters.In the below example we have passed two parameters of int type to function which adds those parameters and returns another integer value as return type. func add(no1:Int, no2:Int)->Int{ return no1+no2 } print(add(no1:100, no2:200)) print(add(no1:200, no2:150)) print(add(no1:300, no2:130)) The above program would return the below output. 300 350 430Function without parameterWithout parameters, we can also have functions. Syntaxfunc funcname() -> datatype {    return datatype }Below is the example for function without parameter. Example func welcomemessage()->String{ return"Welcome" } print(welcomemessage()+ “ to Swift Programming”)Functions with return valuesFunctions are also used as return types to return value string, integer and float. To find the largest and smallest number in a given array, large and small integer data types are declared in ' findingnumbers' function.An array of integer values is initialized. The array is then processed and each value is read and compared for its prior value in the array. If the value is less than that of the earlier, then the argument is stored in'small', otherwise it is stored in'large' argument and the value is returned by the call of a function. func findingnumbers(array:[Int])->(large:Int, small:Int){ var lar = array[0] var sma = array[0] for i in array[1..<array.count]{ if i < sma {          sma = i }elseif i > lar {          lar = i } } return(lar, sma) } let num = findingnumbers(array:[60,43,-52,67,91]) print("Largest number is: \(num.large) and smallest number is: \(num.small)")Functions without return valuesIn some functions, arguments can be declared without return values within the function. The program below declares a and b to support the sum() function. The values for argument a and b are passed inside the function itself by calling the function sum () which removes return values by printing its values. func sum(a:Int, b:Int){ let a = a + b print(a) } sum(a:50, b:5) sum(a:60, b:40) sum(a:34, b:6) The output would be 55 100 40Functions with Optional Return Types Swift introduces 'optional' to resolve problems through the introduction of a safety measure. Take for instance, we declare return values as integer, but what happens if the feature returns a string value or nil value? The compiler returns an error value in that case. To get rid of these problems,'optional' is introduced. Two forms will be' value' and' nil' for optional functions. we  will mention "optional" with the reserved key character ? to see if the value or nil is returned by the tuple.The''Optional'' are used for checking'nil' or garbage values that take up a lot of debugging time and make code efficient and user-readable. func minMax(array:[Int])->(min:Int, max:Int)?{ if array.isEmpty {return nil} var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count]{  ifvalue< currentMin {           currentMin =value }elseifvalue> currentMax {           currentMax =value } } return(currentMin, currentMax) } if let bounds = minMax(array:[8,-6,2,109,3,71]){ print("min is \(bounds.min) and max is \(bounds.max)")  } Local parameter vs External parameterWithin the function alone, names of local parameters are accessed. func example(number: Int) {    print(number) }The func example argument number will be stated as an inner variable because the example () function can be accessed externally. Here the' number' is given as a local variable but the variable is referred to outside of the function with the following declaration : example(number:6) External parameter names enable us to make their purpose clearer by naming function parameters. You can, for instance, name two parameters of the function and call it the following. unc pow(firstArg a:Int, secondArg b:Int)->Int{  var res = a  for _ in1..<b {       res = res * a  }  print(res) return res }  pow(firstArg:5, secondArg:3)Variadic Parameters We can declare the participants as'variadic' parameters if we want to define a function with several arguments. Parameters can be set to variadic by parameter name followed by (····) Example func check<N>(members: N...){ for i in members { print(i) } } check(members:421,3,25) check(members:14.5,32.1, 45.6) check(members:"Hello","Functions","Closures")The constant & variable parameter typeThe parameters are deemed as "constant' by default while the user can also declare the arguments as variables for the functions too. In swift, I / O parameters provide characteristics to preserve parameter values, even if its values are modified after a function gets called. We talked already about the use of the word'let' to declare constant parameters and defining variable parameters with the keyword "var." At the beginning of the function definition, the ‘inout ’keyword for maintaining the Member values is proclaimed.The keyword ' inout ' is derived as its values are passed onto the function as “in” and its values are accessed and modified by its functional body and returned 'out ' to change the original argument.The in-out parameter variables are only carried as an argument because their values are altered in and outside of the function alone. Strings and literals need not be declared as parameters of in-out. ‘&' relates to the argument to the in-out parameter before the variable name. func temp(a1: inout Int, b1: inout Int){ let t = a1    a1 = b1    b1 = t } varno = 2 var co = 10 temp(a1:&no, b1:&co) print("Swapped values are \(no), \(co)")The output of above program would be as follows: Swapped values are 10, 2Function Types as Parameter Types & Return TypesWe can also use function itself as parameter type and return type of any other function. func sum(a:Int, b:Int)->Int{  return a + b  }  var addition:(Int,Int)->Int= sum  print("Result: \(addition(40, 89))") func another(addition:(Int,Int)->Int, a:Int, b:Int){  print("Result: \(addition(a, b))")  }  another(sum,10,20) Nested FunctionsWe can also call a function inside another function. This is called nested function. func calcDecrement(forDecrement total:Int)->()->Int{ var overallDecrement = 0    func decrementer()->Int{       overallDecrement -= total return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement:30) print(decrem())ClosuresClosures are functional blocks that can be used in your code and passed through. Swift closures can be compared with the blocks in the programming languages C and Objective-C or lambda. Closures capture and store any constants and variables from a specific context. It is called closing over constants and variables. Swift manages your entire memory collection management. The global and nested functions are special cases of closure. Closures will fall into three categories: Closures that have a name but do not capture any values are Global Functions. Closures that have a name but also capture values from enclosing functions are called Nested Functions. Closures which are written in a lightweight syntax are usually unnamed and can capture values from surroundings are called closure expressions. In general , Swift's closure expressions have a smooth, straightforward style, with optimizations that promote short, clutter-free syntax.These optimizations include: Inferring context parameter and value types. Single expression closure implicit returns Shorthand argument names Trailing closure syntax Syntax {    (parameters) −> return type in    statements }Example let closureexample={print("Swift Closures")}  closureexample() The below closure example takes two int parameters and returns an integer. {    (Int, Int) −> Int in    Statement1    Statement 2    ---    Statement n } let multiply={  (val1:Int, val2:Int)->Int in   return val1 *val2   } let result = multiply(10,20) print(result)   The above program output would be as follows:  200 Expression in ClosuresClosure expressions are a way of writing short, focused syntax inline closures. Closure expressions provide several syntax optimizations in a shortened form to write closures without loss of clarity or intent. The following instances of closure expressions demonstrate these optimizations by refining a single instance of the sorted(by:)technique over multiple iterations, each of which expresses the same features more succinctly. The Sorted MethodA method called sorted(by:) in Swift's normal library, a known type value range is sorted based on the output from the sorting closure you provide. The sorted(by:) method returns a new array with the correct order of its elements, of the same type and size as the old one.The initial array is not changed with method sorted(by:). The following closing expression examples are used with the sorted(by:) technique to sort an array of string values in inverse alphabetical order. The first array to sort is here. let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]The sort(by:) method acknowledges a closure which needs two arguments with the same type of the array content and returns a Bool value to determine whether the first value must appear before or after the second value after sorting.If the first value comes prior to the second value, the closure of the sorting  has to be returned as true, and otherwise false. This example sorts a string values range, so it needs to be a type characteristic (String, String)-> Bool to close the sorting.One way of closing the sorting process is by writing a standard function of the correct type and transferring it as an argument to the sorted(by:) function: func backward(_ s1: String, _ s2: String) -> Bool {      return s1 > s2  }  var reversedNames = names.sorted(by: backward)  // reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]This is, however, a rather long-winded way of writing what is basically a single-expression function(a > b). In this instance, the inline sorting closure should be written using the syntax of closure expression. reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 })Note that for this inline closure, the parameter statement and return type is identical to the backward:(:) statement function . It is published in both instances as (s1: String, s2: String)-> Bool. However, for the expression of inline closure, the parameters and type of return are written inside, not outside, the curly braces. The keyword in introduces the beginning of the body of the closure. This keyword shows that the definition of the closure parameters and type of return has been completed and the closure body is about to start. The above closure can be written in a single line as well: reversedNames = names.sorted(by: {(s1: String, s2: String) -> Bool in return s1 > s2})Implicit Returns from the Single-Expression ClosuresSingle-expression closures, as in the past example, by omitting the return keyword from their declaration, can implicitly return the outcome of their single expression: reversedNames = names.sorted(by: { s1,s2 in s1 > s2})In this case, the function type of the sorted(by:) method argument makes it clear that a Bool value must be returned by the closure. Since the closure body includes a single expression (s1>s2) returning a Bool value, there is no ambiguity and the return keyword can be omitted. Declaring shorthand name as ClosuresSwift automatically provides shorthand argument names for inline closures that can be used with the names $0, $1, $2, and so on to refer to the closure statements values. Use these shorthand argument names within our closure expressions, you can exclude the closure argument list from the definition and deduce the number and type of the shorthand argument names from the expected function type. Also the keyword “in” can be omitted as its body consists entirely of the sentence of closure: reversedNames = names.sorted(by: {$0 > $1})Closures as Operator functionIn fact, there is an even shorter way to write the expression of closure above. Swift's String type describes its higher-than-operator (>) string-specific execution as a technique that has two String parameters and returns a Bool-type value. This precisely matches the sort of technique required by the procedure sorted(by:). You can therefore simply go through the operator, and Swift will deduce that you want to use its string-specific application: reversedNames = names.sorted(by: >) Closures as Trailers If you need to pass a closure expression to a function as the final argument of the function and the expression closure is long, instead it may be useful to write it as a trailing closure. After the parentheses of the function call, a trailing closure is written, although it is still an argument for the function. You do not write the argument label as part of the function call when using the trailing closure syntax. func someFunctionThatTakesAClosure(closure: () -> Void) { // function body goes here }// Here's how you call this function without using a trailing closure:someFunctionThatTakesAClosure(closure:{  // closure's body goes here  })  // Here's how you call this function with a trailing closure instead:  someFunctionThatTakesAClosure() {  // trailing closure's body goes here } The string-sorting closure from the above section of Closure Expression Syntax can be written as a trailing closure outside the parentheses of the sorted(by the :) method: reversedNames = names.sorted() { $0 > $1 }If you provide a closure expression as function or method’s only argument  and you provide that expression as a trailing closure, you do not need to write a couple of parentheses () after the name of the function or method when calling the feature: reversedNames = names.sorted { $0 > $1 }Capturing Values and Reference TypesWith the help of closures, constants and variables are captured in Swift. It also refers to and modifies the values within the closure body for those constants and variables even if the variables no longer exist. By using the nested function, the capture of constant and variable values is accomplished by composing function with other functions in the body. In Swift, when a constant or variable is stated within a function, the closure also automatically creates a reference to these variables.It also allows  to refer to more than two variables as the following closure: let decrem = calcDecrement(forDecrement: 18) decrem()Here closure reference will point to the same memory block as variables. func calcDecrement(forDecrement total:Int)->()->Int{ var overallDecrement = 200    func decrementer()->Int{       overallDecrement -= total print(overallDecrement) return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement:28) decrem() decrem() decrem()When we run the above program the output would be 172 144 116When calcDecrement is called every time the outer function invokes the decrementer() function and decreases the value by 28 and returns the outcome with the assistance of the calcDecrement outer function. CalcDecrement here functions as a closure.Summary:We have got fair idea of swift's functional and closures with help of this module. Whenever we need to group some statements together performing some specific tasks ,we will be using functional. Swift closures are identical to those of self-contained functions grouped as blocks .Closure expressions in Swift language follow crisp, optimization, and lightweight syntax styles.
logo

Swift Tutorial

Functionals and Closures

A function is a collection of statements to carry out a particular assignment together. A Swift  function may be as easy as a straightforward C function and as complex as  an Objective C function. This enables us to inside function calls to transfer local and global parameter values. 

  • Function declaration: informs the compiler about the name, type of the function, and parameters of the function. 
  • Function Definition: The real function body is provided. 

The "func" keyword is used to define function in Swift . If a function is redefined, one or more values can be added to the function by input parameters, and it processes the functions inside the body , transferring the values back to the functions as return types of output.Each function has a name for the function describing the job performed by this function. In order to use a function, you "call" it by name and pass input values (so-called arguments) that match the parameter types of the function. Also called' tuples ' function parameters. 

Arguments for a function must always be in the same order as the parameter list for the function and the values for return must always be followed by → 

Syntax 

func funcname(Parameters) -> returntype {
   Statement1
   Statement2
   ---
   Statement N
   return parameters
}

Check out the code below. The name of the program is declared as a data string in the ‘program’ function, and if the function is called, the name of the student will be returned. 

func program(name:String)->String{
  return name
}
print(program(name:"Hello"))
print(program(name:"World"))

In the above example function accepts a parameter of string type and also return type is string. The function is invoked by calling function name (here “program”) with parameter name (“name”) and passing value to the parameter.Swift  offers flexible parameters and returns from simple to complex values. In Swift  functions may take several forms, similar to that of C and Objective C. Let's cover that in detail. 

Different forms of Swift functions 

Function with parameter

A function is declared by transferring its parameter values to the function body. We can pass single values as tuples in the function to multiple parameters.In the below example we have passed two parameters of int type to function which adds those parameters and returns another integer value as return type. 

func add(no1:Int, no2:Int)->Int{
return no1+no2
}

print(add(no1:100, no2:200))
print(add(no1:200, no2:150))
print(add(no1:300, no2:130))

The above program would return the below output.

300
350
430

Function without parameter

Without parameters, we can also have functions. 

Syntax

func funcname() -> datatype {
   return datatype
}

Below is the example for function without parameter. 

Example 

func welcomemessage()->String{
return"Welcome"
}
print(welcomemessage()+ “ to Swift Programming”)

Functions with return values

Functions are also used as return types to return value string, integer and float. To find the largest and smallest number in a given array, large and small integer data types are declared in ' findingnumbers' function.An array of integer values is initialized. The array is then processed and each value is read and compared for its prior value in the array. If the value is less than that of the earlier, then the argument is stored in'small', otherwise it is stored in'large' argument and the value is returned by the call of a function. 

func findingnumbers(array:[Int])->(large:Int, small:Int){
var lar = array[0]
var sma = array[0]

for i in array[1..<array.count]{
if i < sma {
         sma = i
}elseif i > lar {
         lar = i
}
}
return(lar, sma)
}

let num = findingnumbers(array:[60,43,-52,67,91])
print("Largest number is: \(num.large) and smallest number is: \(num.small)")

Functions without return values

In some functions, arguments can be declared without return values within the function. The program below declares a and b to support the sum() function. The values for argument a and b are passed inside the function itself by calling the function sum () which removes return values by printing its values. 

func sum(a:Int, b:Int){
 let a = a + b
print(a)
}
sum(a:50, b:5)
sum(a:60, b:40)
sum(a:34, b:6)

The output would be
55
100
40

Functions with Optional Return Types 

Swift introduces 'optional' to resolve problems through the introduction of a safety measure. Take for instance, we declare return values as integer, but what happens if the feature returns a string value or nil value? The compiler returns an error value in that case. To get rid of these problems,'optional' is introduced. 

Two forms will be' value' and' nil' for optional functions. we  will mention "optional" with the reserved key character ? to see if the value or nil is returned by the tuple.The''Optional'' are used for checking'nil' or garbage values that take up a lot of debugging time and make code efficient and user-readable. 

func minMax(array:[Int])->(min:Int, max:Int)?{
if array.isEmpty {return nil}
var currentMin = array[0]
var currentMax = array[0]

for value in array[1..<array.count]{ 
  ifvalue< currentMin { 
         currentMin =value 
}elseifvalue> currentMax { 
         currentMax =value 
} 
} 
return(currentMin, currentMax) 
}
if let bounds = minMax(array:[8,-6,2,109,3,71]){ 
print("min is \(bounds.min) and max is \(bounds.max)") 
} 

Local parameter vs External parameter

Within the function alone, names of local parameters are accessed. 

func example(number: Int) {
   print(number)
}

The func example argument number will be stated as an inner variable because the example () function can be accessed externally. Here the' number' is given as a local variable but the variable is referred to outside of the function with the following declaration : 

example(number:6) 

External parameter names enable us to make their purpose clearer by naming function parameters. You can, for instance, name two parameters of the function and call it the following. 

unc pow(firstArg a:Int, secondArg b:Int)->Int{ 
var res = a 
for _ in1..<b {
      res = res * a 
} 
print(res)
return res
} 
pow(firstArg:5, secondArg:3)

Variadic Parameters 

We can declare the participants as'variadic' parameters if we want to define a function with several arguments. Parameters can be set to variadic by parameter name followed by (····) 

Example 

func check<N>(members: N...){
for i in members {
print(i)
}
}
check(members:421,3,25)
check(members:14.5,32.1, 45.6)
check(members:"Hello","Functions","Closures")

The constant & variable parameter type

The parameters are deemed as "constant' by default while the user can also declare the arguments as variables for the functions too. In swift, I / O parameters provide characteristics to preserve parameter values, even if its values are modified after a function gets called. We talked already about the use of the word'let' to declare constant parameters and defining variable parameters with the keyword "var." At the beginning of the function definition, the ‘inout ’keyword for maintaining the Member values is proclaimed.The keyword ' inout ' is derived as its values are passed onto the function as “in” and its values are accessed and modified by its functional body and returned 'out ' to change the original argument.The in-out parameter variables are only carried as an argument because their values are altered in and outside of the function alone. Strings and literals need not be declared as parameters of in-out. ‘&' relates to the argument to the in-out parameter before the variable name. 

func temp(a1: inout Int, b1: inout Int){
  let t = a1
   a1 = b1
   b1 = t
}
varno = 2
var co = 10
temp(a1:&no, b1:&co)
print("Swapped values are \(no), \(co)")

The output of above program would be as follows: 

Swapped values are 10, 2

Function Types as Parameter Types & Return Types

We can also use function itself as parameter type and return type of any other function. 

func sum(a:Int, b:Int)->Int{ 
  return a +} 
var addition:(Int,Int)->Int= sum 
print("Result: \(addition(40, 89))")

func another(addition:(Int,Int)->Int, a:Int, b:Int){ 
print("Result: \(addition(a, b))") 
} 
another(sum,10,20) 

Nested Functions

We can also call a function inside another function. This is called nested function. 

func calcDecrement(forDecrement total:Int)->()->Int{
var overallDecrement = 0
   func decrementer()->Int{
      overallDecrement -= total
return overallDecrement
}
return decrementer
}
let decrem = calcDecrement(forDecrement:30)
print(decrem())

Closures

Closures are functional blocks that can be used in your code and passed through. Swift closures can be compared with the blocks in the programming languages C and Objective-C or lambda. Closures capture and store any constants and variables from a specific context. It is called closing over constants and variables. Swift manages your entire memory collection management. The global and nested functions are special cases of closure. Closures will fall into three categories: 

  • Closures that have a name but do not capture any values are Global Functions. 
  • Closures that have a name but also capture values from enclosing functions are called Nested Functions. 
  • Closures which are written in a lightweight syntax are usually unnamed and can capture values from surroundings are called closure expressions. 

In general , Swift's closure expressions have a smooth, straightforward style, with optimizations that promote short, clutter-free syntax.These optimizations include: 

  • Inferring context parameter and value types. 
  • Single expression closure implicit returns 
  • Shorthand argument names 
  • Trailing closure syntax 

Syntax 

{
   (parameters) −> return type in
   statements
}

Example 

let closureexample={print("Swift Closures")} 
closureexample()

The below closure example takes two int parameters and returns an integer.
{
   (Int, Int) −> Int in
   Statement1
   Statement 2
   ---
   Statement n
}

let multiply={ 
(val1:Int, val2:Int)->Int in 
 return val1 *val2  
}

let result = multiply(10,20)
print(result)
 
The above program output would be as follows: 
200 

Expression in Closures

Closure expressions are a way of writing short, focused syntax inline closures. Closure expressions provide several syntax optimizations in a shortened form to write closures without loss of clarity or intent. The following instances of closure expressions demonstrate these optimizations by refining a single instance of the sorted(by:)technique over multiple iterations, each of which expresses the same features more succinctly. 

The Sorted Method

A method called sorted(by:) in Swift's normal library, a known type value range is sorted based on the output from the sorting closure you provide. The sorted(by:) method returns a new array with the correct order of its elements, of the same type and size as the old one.The initial array is not changed with method sorted(by:). The following closing expression examples are used with the sorted(by:) technique to sort an array of string values in inverse alphabetical order. The first array to sort is here. 

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

The sort(by:) method acknowledges a closure which needs two arguments with the same type of the array content and returns a Bool value to determine whether the first value must appear before or after the second value after sorting.If the first value comes prior to the second value, the closure of the sorting  has to be returned as true, and otherwise false. This example sorts a string values range, so it needs to be a type characteristic (String, String)-> Bool to close the sorting.One way of closing the sorting process is by writing a standard function of the correct type and transferring it as an argument to the sorted(by:) function: 

func backward(_ s1: String, _ s2: String) -> Bool { 
    return s1 > s2 
} 
var reversedNames = names.sorted(by: backward) 
// reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

This is, however, a rather long-winded way of writing what is basically a single-expression function(a > b). In this instance, the inline sorting closure should be written using the syntax of closure expression. 

reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})

Note that for this inline closure, the parameter statement and return type is identical to the backward:(:) statement function . It is published in both instances as (s1: String, s2: String)-> Bool. However, for the expression of inline closure, the parameters and type of return are written inside, not outside, the curly braces. 

The keyword in introduces the beginning of the body of the closure. This keyword shows that the definition of the closure parameters and type of return has been completed and the closure body is about to start. The above closure can be written in a single line as well: 

reversedNames = names.sorted(by: {(s1: String, s2: String) -> Bool in return s1 > s2})

Implicit Returns from the Single-Expression Closures

Single-expression closures, as in the past example, by omitting the return keyword from their declaration, can implicitly return the outcome of their single expression: 

reversedNames = names.sorted(by: { s1,s2 in s1 > s2})

In this case, the function type of the sorted(by:) method argument makes it clear that a Bool value must be returned by the closure. Since the closure body includes a single expression (s1>s2) returning a Bool value, there is no ambiguity and the return keyword can be omitted. 

Declaring shorthand name as Closures

Swift automatically provides shorthand argument names for inline closures that can be used with the names $0, $1, $2, and so on to refer to the closure statements values. 

Use these shorthand argument names within our closure expressions, you can exclude the closure argument list from the definition and deduce the number and type of the shorthand argument names from the expected function type. Also the keyword “in” can be omitted as its body consists entirely of the sentence of closure: 

reversedNames = names.sorted(by: {$0 > $1})

Closures as Operator function

In fact, there is an even shorter way to write the expression of closure above. Swift's String type describes its higher-than-operator (>) string-specific execution as a technique that has two String parameters and returns a Bool-type value. This precisely matches the sort of technique required by the procedure sorted(by:). You can therefore simply go through the operator, and Swift will deduce that you want to use its string-specific application: 

reversedNames = names.sorted(by: >) 

Closures as Trailers 

If you need to pass a closure expression to a function as the final argument of the function and the expression closure is long, instead it may be useful to write it as a trailing closure. After the parentheses of the function call, a trailing closure is written, although it is still an argument for the function. You do not write the argument label as part of the function call when using the trailing closure syntax. 

func someFunctionThatTakesAClosure(closure: () -> Void) { 
// function body goes here 
}
// Here's how you call this function without using a trailing closure:


someFunctionThatTakesAClosure(closure:{ 
// closure's body goes here 
}) 
// Here's how you call this function with a trailing closure instead: 
someFunctionThatTakesAClosure() { 
// trailing closure's body goes here
} 

The string-sorting closure from the above section of Closure Expression Syntax can be written as a trailing closure outside the parentheses of the sorted(by the :) method: 

reversedNames = names.sorted() { $0 > $1 }

If you provide a closure expression as function or method’s only argument  and you provide that expression as a trailing closure, you do not need to write a couple of parentheses () after the name of the function or method when calling the feature: 

reversedNames = names.sorted { $0 > $1 }

Capturing Values and Reference Types

With the help of closures, constants and variables are captured in Swift. It also refers to and modifies the values within the closure body for those constants and variables even if the variables no longer exist. By using the nested function, the capture of constant and variable values is accomplished by composing function with other functions in the body. 

In Swift, when a constant or variable is stated within a function, the closure also automatically creates a reference to these variables.It also allows  to refer to more than two variables as the following closure: 

let decrem = calcDecrement(forDecrement: 18)
decrem()

Here closure reference will point to the same memory block as variables. 

func calcDecrement(forDecrement total:Int)->()->Int{
var overallDecrement = 200
   func decrementer()->Int{
      overallDecrement -= total
print(overallDecrement)
return overallDecrement
}
return decrementer
}

let decrem = calcDecrement(forDecrement:28)
decrem()
decrem()
decrem()

When we run the above program the output would be 

172
144
116

When calcDecrement is called every time the outer function invokes the decrementer() function and decreases the value by 28 and returns the outcome with the assistance of the calcDecrement outer function. CalcDecrement here functions as a closure.

Summary:

We have got fair idea of swift's functional and closures with help of this module. Whenever we need to group some statements together performing some specific tasks ,we will be using functional. Swift closures are identical to those of self-contained functions grouped as blocks .Closure expressions in Swift language follow crisp, optimization, and lightweight syntax styles.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Rashid

I am interested in the learning of swift and coding

Arlin Burns

Is this included in csm training and certification or sold separately?

Sneha Agrawal

I am interested in advanced level training of SWIFT and coding.

Suggested Tutorials

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More

Python Tutorial

Python Tutorial