X
22Jan

Swift Closures

A closure is a kind of anonymous(no name) function that gets stored as a variable so it can be called later on and has the special ability to remember the state of your program when you used it.Closures are typically enclosed in curly braces { } and are defined by a function type () -> (), where -> separates the arguments and the return type, followed by the 'in' keyword which separates the closure header from its body.Constants and variable references defined inside the functions are captured and stored in closures.

The general syntax for declaring closures is

ScreenShot1939-11-03...

 

Closures can be defined in three ways

1. Global functions:- These are treated as a closures which have a name but it does not capture any value.

2. Nested functions:-  These are also treated as a closures which have name and it can captures values from the functions which are enclosed within the function.

3. Closure expressions:-  These are the unnamed closures and written in lightweight context and that can capture values from their surrounding context.

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 infered.

ScreenShot1939-11-03...

Here the 'in' keyword is used to separate the return Type and statements inside the closure.The closure accepts parameters and can return value.

 


Swift Closures Examples

Following is the example of showing different ways of using closures in swift programming language.

1. Closure without parameters and return types

ScreenShot1939-11-03...

 

2. Closure with only return type

ScreenShot1939-11-03...

 

3. Closure with only parameter type

ScreenShot1939-11-03...

 

4. Closure with single parameter and return type

ScreenShot1939-11-03...

 

5. Closure with multiple parameters and return types

ScreenShot1939-11-03...

If we observe above example we defined multiple closures with or without parameters and return types based on our requirements.

 


Simplifying Closure Syntax

Sort Elements in Swift with Closures

With the help of sorted method in swift we can sort elements of arrays or lists in closures.The sorted method will sort array elements in ascending order and return it as a new array list with same elements but in particular order.

Example of sorting array elements using Swift closures.

ScreenShot1939-11-03...

 

Inferring Type from Context in Swift Closure

we can use type inference to make more short syntax for the declaration of closure. For type inference we just remove the return type in closure.In closures after parameter declaration we can remove (->) sign and return type to create short form of using closures in swift.When we will run the application swift automatically judge the type of inference using input parameters in closures.

Example of inferring type from closure context in swift programming language

ScreenShot1939-11-03...

 

Swift Closures with Single-Expression and Implicit Returns

This is the new version of writing a sorted closure.

ScreenShot1939-11-03...

Single expression closures are returning the result of their expression after omitting the return keyword from declaration.This is how we can return result of single expression closures with implicit returns in swift.

 

Using Shorthand syntax

Swift automatically provides a shorthand argument names to inline closures,which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.we are able to omit the parameter and return type along with the in and return keywords. By refering to each name of the array as $0, we are using Swift’s automatic parameter naming to shorten the amount of code we have to write.

ScreenShot1939-11-03...

This is how we can shorthand argument names in closures to omit closures arguments list while declaring in swift programming language.

 

Swift Closures As a Reference Types

In swift closures are the reference types that means if we assign one closure to more than one variable or constants then those variables or constants will refer to the same closure.

ScreenShot1939-11-03...

 

 

Trailing Closures 

The Swift programming language defines a concept known as trailing closures. The idea is simple. If you pass a closure as the last argument of a function, you can place that closure outside the parentheses of the function call. The following example demonstrates how this works.

ScreenShot1939-11-03...

The argument label onSuccess is not there in the function call. Even though the closure is included in the function parameters list, swift will take it out of the parameter block to make the code more readable.

 

Completion Handlers 

A completion handler is a type of Trailing Closure. It gets passed to a function as an argument and then called when that function is done.The point of a completion handler is to tell whatever is calling that function that it’s done and optionally to give it some data or an error. Sometimes they’re called callbacks since they call back to whatever called the function they’re in.

The use of Completion Handler is to notify the user when the download completed.


 We will create a closure which will be called within a function.

ScreenShot1939-11-03...

We may pass a closure block directly when we execute the downloadFile function. Notice the trailing closure block.

ScreenShot1939-11-03...

 

Conclusion

Closures are an important concept, and we will use them often in Swift. Closures enable us to write flexible, dynamic code that is easy both to write and to understand.

Related

Swift Mapping and Flat Mapping

In this blog post, I will introduce some of useful tips and techniques of using swift mapping and fl...

Read More >

Access Control in Swift 3

End of this blog you will be able to understand the Access control specifiers open, public,internal,...

Read More >

Share

Post a Comment

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
  • Key Metrics to Measure DevOps Success

    DevOps words means many things to many people and all the definitions might be partly right. DevOps is all about continuously seeking feedback, understanding challenges, and improving the way the soft...
  • Bulk Export Import Test Cases to Azure DevOps Test Plans using CSV file

    As a user of Azure DevOps Test Plans or TFS Test Management for manual testing, from a long time everyone including me had a wish, that copy of test cases from excel or csv file along with test steps ...
  • Azure DevOps Overview

    Now a days Azure DevOps is very famous with IT and Operations team along with developers, so what is Azure DevOps? It is a Software as a service (SaaS) platform from Microsoft that provides features r...
  • Volume Management in Kubernetes

    Since pods created in k8s are ephemeral, we are able to get the data as long as pods are alive, but if pods are terminated data stored in it completely lost and it cannot get back, for that we need to...
Monthly Archive
Subscribe
Name

Text/HTML
Text/HTML
Contact Us
  • *
  • *