Whats the difference between these closures?
let closureA: () -> ()
and
let closureB: () -> Void
In Swift, Void is an typealias for an empty tuple, (). typealias Void = () The empty tuple type. This is the default return type of functions for which no explicit return type is specified.
Difference between Function and ClosureFunction is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.
There are two kinds of closures: An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.
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're defined. This is known as closing over those constants and variables.
If you look into headers, you will see that Void is typealias for (),
/// The empty tuple type. /// /// This is the default return type of functions for which no explicit /// return type is specified. typealias Void = ()
You can verify that using playground like this,
let a = Void() print(a) // prints ()
Update
If you wish to see the declaration of Void in header file, in the above code, type the code below in swift playground or xcode editor like so,
let a: Void = ()
Then, cmd + click on the "Void" keyword in above expression, you will be taken to the header file where you can actually see the declaration for Void.
The document has been updated with more information which is like this,
/// The return type of functions that don't explicitly specify a return type; /// an empty tuple (i.e., `()`). /// /// When declaring a function or method, you don't need to specify a return /// type if no value will be returned. However, the type of a function, /// method, or closure always includes a return type, which is `Void` if /// otherwise unspecified. /// /// Use `Void` or an empty tuple as the return type when declaring a /// closure, function, or method that doesn't return a value. /// /// // No return type declared: /// func logMessage(_ s: String) { /// print("Message: \(s)") /// } /// /// let logger: (String) -> Void = logMessage /// logger("This is a void function") /// // Prints "Message: This is a void function" public typealias Void = ()
Same. It's just a typealias so it works exactly the same.
typealias Void = ()
Sounds like Erica Sadun and Apple are trying to stick with Void: http://ericasadun.com/2015/05/11/swift-vs-void/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With