Are there any possible explicit uses of instances (values) of empty tuples (), i.e., of instances of typealias 'Void'?

后端 未结 2 1634
情书的邮戳
情书的邮戳 2020-12-12 00:42

Question:

  • Are there any possible explicit uses for the empty tuple (), as a value (and not as a type) in Swift 2.x?
2条回答
  •  再見小時候
    2020-12-12 01:30

    Suppose you have two functions overloading the same name:

    func foo()
    func foo() -> Int
    

    The first doesn't return anything, the second returns some kind of value. Attempting to call either of these will in most cases get you a compiler error about ambiguity.

    foo()
    let a = foo()
    

    You'd think that the compiler would know that the first call unambiguously refers to the first function, because it assumes no return value. But in actuality, the return type of a function with no declared return type is Void, or (). So the first call is actually more like this:

    let _ = foo()
    

    And absent a type annotation for the discarded lvalue, the compiler can't infer which foo to call. You can use explicit type annotations to disambiguate:

    let b: Void = foo()
    let c: Int = foo() 
    

    Okay, it's not a very great or common use case for Void, because it's a situation you'd tend to avoid getting into in the first place. But you asked for a use... and it is a use of () as a value and not just a type, because you can retrieve it from b after assignment (for all the good that does you).

    Just beware, when you look deeply into the Void, the Void also looks into you. Or something like that.

提交回复
热议问题