Difference between returning Void and () in a swift closure

巧了我就是萌 提交于 2019-12-18 11:23:05

问题


Whats the difference between these closures?

let closureA: () -> ()

and

let closureB: () -> Void

回答1:


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()
println(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 = ()



回答2:


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/




回答3:


There is no difference at all

Void is an alias for ():

typealias Void = ()


来源:https://stackoverflow.com/questions/27422453/difference-between-returning-void-and-in-a-swift-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!