这些关闭之间有什么区别?
let closureA: () -> ()
Run Code Online (Sandbox Code Playgroud)
和
let closureB: () -> Void
Run Code Online (Sandbox Code Playgroud)
San*_*eep 26
如果您查看标题,您会看到Void是()的类型,
/// The empty tuple type.
///
/// This is the default return type of functions for which no explicit
/// return type is specified.
typealias Void = ()
Run Code Online (Sandbox Code Playgroud)
您可以使用这样的游乐场验证
let a = Void()
println(a) // prints ()
Run Code Online (Sandbox Code Playgroud)
更新
如果你想在头文件中看到Void的声明,在上面的代码中,在swift playground或xcode编辑器中键入下面的代码,如下所示,
let a: Void = ()
Run Code Online (Sandbox Code Playgroud)
然后,cmd +点击上面表达式中的"Void"关键字,您将进入头文件,您可以在其中实际看到Void的声明.
该文件已更新,有更多信息,如下所示,
Run Code Online (Sandbox Code Playgroud)/// 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 = ()
相同的。它只是一个类型别名,所以它的工作原理完全相同。
typealias Void = ()
Run Code Online (Sandbox Code Playgroud)
听起来 Erica Sadun 和苹果正试图坚持使用 Void: http://ericasadun.com/2015/05/11/swift-vs-void/
如果您到达此处是因为遇到诸如 之类的错误Cannot convert value of type 'Void.Type' to specified type 'Void',那么考虑以下内容可能会有所帮助:
()可能意味着两件事:
()可以是一个类型 - 空元组类型,与 相同Void。()可以是一个值 - 一个空元组,与 相同Void()。就我而言,我希望更改()为Void,但这导致了上述错误。解决这个问题意味着要么将其保留为()或使用Void(). 后者可以放入全局常量中let void = Void(),然后您就可以使用void. 这是否是一种好的做法/风格,还有待争论。
| 归档时间: |
|
| 查看次数: |
3708 次 |
| 最近记录: |