Closures in Swift - Part 1
Closures:
Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store references to any constants and variables from the context in which they are defined. Swift handles all of the memory management of capturing for you.
Declaration:
You can declare as below:
{ (parameters) -> return type in
statements
}
The parameters in closure expression syntax can be in-out parameters, but they can’t have a default value.
A simple closure can be declared as below as well
let newClosures = {
print("This is new basic closure which very simple to create and call")
}
we can call using like this newClosures().
Closure With Parameter:
we passed the parameter in the closure and can pass the string as below. The basic different closure and function is closure do not use "Argument Label" while defining and calling.
let newClosures = { (closureName: String) in
print("This is new basic closure which very simple to create and call. The name \(closureName)")
}
newClosures("Pretty Closure") //result: This is new basic closure which very simple to create and call. The name Pretty Closure
Return From Closure:
you can return from closure as below
let returnClosures = { (closureName: String)-> String in
return "This is new basic closure which very simple to create and call. The name \(closureName)"
}
let result = returnClosures("Return Closure")
print(result)
Closure as Parameter:
we can pass the closures as a parameter which will execute in the function.
let closure = { print("I am going demo clsoure as Parameter") }
func closureAsParameterInFunction (action: ()-> Void) {
print("Before call")
action()
print("After call")
}
closureAsParameterInFunction(action: closure)
Trailing Closure Syntax:
If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead.
func trailingClosureSyntax (action: ()-> Void) {
print("Before call")
action()
print("After call")
}
A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.
We can call as below:
trailingClosuresSyntax () {
print("Trailing Closure Executing")
}
Trailing Closures With Parameter: When we have parameter in trailing closure syntax:
func trailingClosureSyntax (action: (String)-> Void) {
print("Before call")
action("Trailing Closure Executing With Parameter")
print("After call")
}
trailingClosureSyntax { (note:String) in
print(note)
}
Closures With Parameter when Return Values: we can return from closure as well.
func trailingClosuresSyntax (action: (String)-> String) {
print("Before call")
let retrunValue = action("With Return")
print(retrunValue)
print("After call")
}
trailingClosuresSyntax { (note:String) -> String in
return "Trailing Closure Executing With Parameter and \(note)"
}
Shorthand Parameter:
func trailingClosuresSyntax (action: (String)-> String) {
print("Before call")
let returnValue = action("With Return")
print(retrunValue)
print("After call")
}
trailingClosuresSyntax { (note:String) -> String in
return "Trailing Closure Executing With Parameter and \(note)"
}
As per the above code, trailing closure knows the parameter type and return type so we can write it as below
trailingClosureSyntax { (note) in
"Trailing Closure Executing With Parameter and \(note)"
}
Note: swift provide the closure parameter name automatically with numbers and it starts from 0 and we can access "$0" in the place parameter name.
trailingClosuresSyntax {
"Trailing Closure Executing With Parameter and \($0)"
}
"$0" used as a shorthand operator. Now if there will more than one parameter then we can access the with "$0", "$1", "$2" and so on.
Return Closure From Function:
As we can pass the closure to a function and same way we can return closure from function as below:
func closreReturnFromFunction( )-> (String) ->Void {
return {
print("I am accessing the parameter with shorthand \($0)")
}
}
let result = closreReturnFromFunction()
result("Operator")
or
let result = closreReturnFromFunction()("Operator")
Closure Capturing Value:
Closure captures the value inside the scope even if that is not there.
func closreReturnFromFunction( ) -> (String) -> Void {
var counter = 1
return {
print("I am accessing the parameter with shorthand \($0) with \(counter)")
counter += 1
}
}
let result = closreReturnFromFunction()
result("Operator")
result("Operator")
result("Operator")
result("Operator")
Result:
I am accessing the parameter with shorthand Operator with 1
I am accessing the parameter with shorthand Operator with 2
I am accessing the parameter with shorthand Operator with 3
I am accessing the parameter with shorthand Operator with 4
So here is the closure details. I hope you would like it. Please let me know your feedback. Go through my previous blog for more details swift.
Enjoy Swift Code 😊
Its good and Informative.Thank you for posting this article.
ReplyDeleteios app development course
I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up
ReplyDeleteDigital Marketing Training in Chennai
Digital Marketing Course in Chennai
This post is so useful and informative. Keep updating with more information.....
ReplyDeleteSwift Developer
Swift Developer Salary
Your content is good for ios Development
ReplyDeleteand it is very helpful and informative content.
as your blog, we know about working on optimizing the relationships between the program and the programmer.
If you find the IOS Development COMPANY in India then Sapphire Software Solutions is the best place for you.