Introduction to Closures In Swift

Posted By : Aditya Kumar Sharma | 21-Dec-2017

 

What are Closures?

 

Closures are enclosed in curly braces {} without func keyword and func name. They are defined by function type ()-> ()

{ (params) -> returnType in
  statements
}

in keyword separates closure header with its body.

 

 

Function VS Closures

 

Function

Closures

has no in keyword

has in keyword

has a name

has no name

has func keyword

has no func keyword

 

Define and Call

 

That’s how we define function and closures:

func callAFunc() { }

var callAClosure = { () -> () in }

 

Closure is been stored in a variable so that it can be called when required.

 

Calling functions and closures:

callAFunc()

callAClosure()
 

 

Both are identical.

 

Function to Closure

 

Let’s convert the below function to closure.

func multiplyNumbers(a: CGFloat, b: CGFloat) -> String {
	return “Result is: \(a * b)”
}

 

Steps:

 

  • Removing curly braces
func multiplyNumbers(a: CGFloat, b: CGFloat)  -> String 
	return “Result is: \(a * b)”
 
  • Add in keyword between argument and body

func multiplyNumbers(a: CGFloat, b: CGFloat)  -> String in
	return “Result is: \(a * b)”
  • Removing func name and keyword

(a: CGFloat, b: CGFloat)  -> String in
	return “Result is: \(a * b)”
 
  • Put all in curly braces

{ (a: CGFloat, b: CGFloat)  -> String in
	return “Result is: \(a * b)”
     }

 

It’s done. Now we can assign this closure to a variable and call it whenever required.

 
var multiply = { (a: CGFloat, b: CGFloat)  -> String in
	return “Result is: \(a * b)”
}

multiply(126.43,256.566)

Thanks 

About Author

Author Image
Aditya Kumar Sharma

Aditya is a bright iOS developer, have knowledge of objective C, swift, swift 3, JSON, Core data and iPhone development. Apart from that he loves to travel and explore new things.

Request for Proposal

Name is required

Comment is required

Sending message..