Difference between returning Void and () in a swift closure

前端 未结 4 1407
灰色年华
灰色年华 2020-12-25 12:53

Whats the difference between these closures?

let closureA: () -> ()

and

let closureB: () -> Void
相关标签:
4条回答
  • 2020-12-25 13:13

    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 = ()
    
    0 讨论(0)
  • 2020-12-25 13:20

    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/

    0 讨论(0)
  • 2020-12-25 13:22

    If you arrived here because you got an error such as Cannot convert value of type 'Void.Type' to specified type 'Void', then it might be useful to consider that:

    () can mean two things:

    1. () can be a type - the empty tuple type, which is the same as Void.
    2. () can be a value - an empty tuple, which is the same as Void().

    In my case I was looking to change () to Void, but this caused the error mentioned above. Solving it would either mean just keeping it as () or using Void(). The latter can be put in a global constant let void = Void() and then you can just use void. Whether this is a good practice / style, is up for debate.

    0 讨论(0)
  • 2020-12-25 13:26

    There is no difference at all

    Void is an alias for ():

    typealias Void = ()
    
    0 讨论(0)
提交回复
热议问题