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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.