Differrence between closure and function as argument in swift
In swift there really isn't any difference between functions and closures. A closure is an anonymous function (A function with no name.) That's about it, other than the syntax differences you noted.
In Objective-C functions and blocks/closures ARE different.
Difference between Closure Functions and Functions
Closure:
- Closure is a block of code, treat it like an unnamed function.
- When a closure is passed as an argument, the closure is not evaluated till the code inside the function invokes the argument.
Auto closure:
- Auto closure is just a closure which packages the parameter values along with it.
- When you define an autoclosure, there would be no parameters to the closure.
Difference between fCheckGender
and cCheckGender
:
fCheckGender
takes aString
value as an argument.cCheckGender
takes closure as an argument.- When
cCheckGender
is invoked, the closure is passed an argument, at this point, the closure is only passed as an argument, the closure is not executed. Only when the closure parameter is used inside the function, the closure gets executed.
The example you have stated might not be the best one to demonstrate the difference.
Let's consider a different example:
Example:
func add(a: Int, b: Int) -> Int {
print("add")
return a + b
}
func f1(pValue: Int) {
print("f1")
print("value = \(pValue)")
}
func f2(pClosure: (Int, Int) -> Int, pA: Int, pB: Int) {
print("f2")
let value = pClosure(pA, pB)
print("value = \(value)")
}
//In autoclosure the closure always takes no parameters, because the closure is packaged with parameter values while invoking
func f3(pClosure: @autoclosure () -> Int) {
print("f3")
let value = pClosure()
print("value = \(value)")
}
f1(pValue: add(a: 10, b: 20))
print("=====================\n")
f2(pClosure: add, pA: 10, pB: 20)
print("=====================\n")
f3(pClosure: add(a: 10, b: 20))
print("=====================\n")
Output:
add
f1
value = 30
=====================
f2
add
value = 30
=====================
f3
add
value = 30
=====================
Explanation of example:
- In the function f1 pValue is an Int value.
- So when f1 is invoked, the add is evaluated
- In the functions f2 and f3 pClosure is a closure.
- pClosure (closure) is not evaluated till it is invoked inside the function.
Note:
- Focus on
f3
first which accepts a closure as the argument. - Once you fully understand
f3
, then examinef2
. - Auto closure captures the parameter values when it is invoked and later uses it.
Why and when do we need to pass a closure instead of a value:
- There might be a scenario, where you would like to defer the execution of
add
till the time the functionf2
invokes it. - There might be a scenario, where you make an asynchronous request and you want a piece of code to execute when the request completes. In this case you might pass a closure. (Closure need not always return a value, it is an unnamed function, so it can accept parameters)
Why and when do we need to an autoclosure:
- When you want to defer the execution of
add
and also capture the value of it's parameters.
Suggestion:
- Though time consuming, it is best for you to go through the Swift documentation from the beginning to fully understand it.
Reference:
As Hamish has pointed please read about closures, then auto closures from https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
What is the difference between functions and closures?
Functions are, in fact, just named closures. The following are at least conceptually equivalent:
let foo = { println("hello") }
func foo()->(){ println("hello") }
This gets a little more complicated in the case of using func
to declare methods, as there's some interesting bits of sugar added regarding the automatic insertion of public named parameters, etc. func myMethod(foo:Int, bar:Int, baz:Int)
becomes func myMethod(foo:Int, #bar:Int, #baz:Int)
, for example.
But it's still true that even methods are just a specific case of closures, and if it's true of closures, it's true of functions and methods as well.
What's the difference between closures and callbacks in Swift?
They are two completely different, although compatible, concepts. A callback is a hook for a function to be attached to so that when an action is needed the function can be called to provide a result or affect. A closure is a function that captures local variables to be used in a scope outside of the local scope. A closure can be a callback just like any other function can be a callback but it's not limited to that use.
In your quote they are talking about how you can use a closure for the callback. In that case the compiler can infer the function signature (types of parameters and return) from the context.
Note that this has very little to do with Objective-C blocks. Swift and Objective-C are two completely different languages and blocks and closures are two different implementations of similar concepts.
What is the difference between swift variable and function when use closure in variable?
A variable holds/references a value; a function is a value. Thus variables can hold/reference numbers, strings, instances and, in some languages, functions. Languages that allow variables to hold/reference functions are languages with 'first class functions'
The advantage of closures is that they 'capture' values in their 'lexical scope'. For example, say you need a callback function that executes when some computation completes. You want the callback to dismiss a view controller and log some information:
class MyViewController : ViewController {
func takeAction (message:String) {
// do some stuff, then
doComputation {
self.dismissViewController()
NSLog ("took action: \(message)")
}
}
}
In the above, the argument to doComputation
is a closure; it captures the values bound to self
and message
from the closure's lexical environment.
Swift any difference between Closures and First-Class Functions?
These notions are orthogonal. They are not directly related; they are two facts about functions in Swift.
Functions are first-class. This means they can be passed around — assigned as variables, passed into function parameters as arguments, and passed out of functions as results.
Functions are closures. This means that, at the point of definition, they capture the environment referred to inside the function body but declared outside the function body.
Here is an example (from a playground):
func multiplierMaker(i:Int) -> (Int) -> (Int) {
func multiplier(ii:Int) -> (Int) {
return ii*i
}
return multiplier
}
let g = multiplierMaker(10)
g(2) // 20
Think about the function multiplier
:
The fact that
multiplier
can be returned as the result of the functionmultiplierMaker
, and assigned tog
, and that it has a well-defined type(Int) -> (Int)
, is because functions are first-class.The fact that, when 10 is passed into
multiplierMaker
, the resultingmultiplier
function multiplies its parameter by 10, even when assigned tog
and called later, is because functions are closures.
(Notice that this has nothing to do with anonymous functions. All answers or statements leading you to believe that closures have to do with anonymous functions are wrong. There are no anonymous functions in this example. An anonymous function is a closure, but only because all functions are closures.)
Swift: definition and syntax of functions vs. closures
1: It's a closure.
Examples:
func aFunction() -> () {
// do something
}
let aClosure:() -> () = {
// do something
}
Functions are actually a special case of closures. You can write a
closure without a name by surrounding code with braces ({}). Use in to
separate the arguments and return type from the body.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
2: "in" is just the notation chosen to represent where the arguments/return type end, and the body of the closure begins. It has nothing to do with inout.
How to pass closure with argument as argument and execute it?
Please make your "what-you-have-now" code error free.
Assuming your class A
like this:
class A {
typealias ClosureType = ()->Void
var closure: ClosureType?
init(closure: ClosureType?) {
self.closure = closure
//`closure` would be used later.
}
//To use the closure in class A
func someMethod() {
//call the closure
self.closure?()
}
}
With A
given above, you need to rewrite your class B
as:
class B {
private(set) var a: A!
init() {
//initialize all instance properties till here
a = A(closure: {[weak self] in self?.action(1)})
}
func action(i: Int) {
//...
}
}
Is it complusory to use in keyword in closure? If no then what is the syntax wise difference between closure and computed property in swift?
greet
is a closure. A computed property is
var greet : Int {
return 4+3
}
greet // without parentheses
And "in" in closure is also not compulsory if a parameter is passed (by the way the return
keyword is not compulsory)
var greet = { x in
4+x
}
greet(4)
unless you use the shorthand syntax
var greet = {
4+$0
}
greet(4)
Related Topics
iOS Swift Nsmutabledata Has No Member Appendstring
How to Handle Oauth-Style Log Ins with Imessage Apps in iOS 10, Xcode 8
Turning on Thread Sanitizer Results in Signal Sigabrt
Pass Data from View Controller to Child Controller in Swift
How to Use a Generic Class Without the Type Argument in Swift
Skspritenode Does Not Let Touches Pass Through When Isuserinteractionenabled False
Uiview Rounded Corner - Swift 2.0
Avaudiocompressedbuffer to Uint8 Array and Vice Versa
Swiftui How Add Custom Modifier with Callback
Change Title of a Navigation Bar Button Item
Swift Uinavigation Bottom Line and Shadow Remove Without Navbar Color Change
Load Large 3D Object .Scn File in Arscnview Aspect Fit in to the Screen Arkit Swift iOS
How to Test If "Allow Full Access" Permission Is Granted from Containing App
Uidropinteractiondelegate Performdrop Not Called
Swift Nfc Mifare - Nfciso7816Apdu Sendmifare Command Not Supported