Swift中的未知函数返回类型。 ()?

时间:2018-03-18 00:20:13

标签: swift

在函数类型中,您可以编写

()->()?

它建立得很好!什么是()?

2 个答案:

答案 0 :(得分:3)

() -> ()?定义更高阶的类型,将空元组 ()作为参数,并返回空元组的Optional Optional<()>或者,?使用Optional糖,只需()?

有一个名为Void的空元组的typedef,所以以下所有都是等效的高阶类型:

() -> ()?
() -> Optional<()>
() -> Void?
() -> Optional<Void>

应用于闭包时的示例:

// c1 through c4 all have the same type, but use
// typedefs (Void) or optional sugar (?) for variations.
var c1: () -> ()? = { return nil }
let c2: () -> Optional<()> = c1
let c3: () -> Void? = c1
let c4: () -> Optional<Void>? = c1

请注意,()也是空元组的实例(除了用作 type 之外),这意味着我们可以 - 分配例如上面的可变闭包c1返回 ()

c1 = { return () }
c1 = { return .some(()) }

另一方面,由于Void只是空元组类型的typedef,我们需要显式实例化非可选(命名)Void实例,如果我们想要返回“空元组实例”而不实际使用()值(并且仅使用Void typedef):

c1 = {
    let v: Void
    return v
}

通常声明一个非可选的不可变属性而不为其指定是Swift中的一个错误,但由于Void typedef,即空元组,只能容纳一个值(()),Swift编译器似乎足够聪明,允许省略将此唯一可能的值分配给上面的v(或者,对于非常特殊的空元组类型的特殊情况)。

最后,请注意所有非可选的() - 返回闭包或函数都可以省略返回值,并且在函数声明中,也省略了类型:

// Now studying the case of non-optional () return
var c6: () -> () = { print("Implicit () return") }
func f1() { print("Implicit return type, implicit () return") }
func f2() { print("Implicit return type, explicit () return"); return () }
func f3() -> () { print("Explicit return type, implicit () return") }
func f4() -> () { print("Explicit return type, explicit () return"); return () }
c6 = f1
c6 = f2
c6 = f3
c6 = f4
let emptyTupleInstance = c6() // "()"

答案 1 :(得分:1)

是。

()?

表示可选的void。我曾经把它写成(虚空)?

不要认为可选和无效是一回事。他们绝对不是。基本上:'void'是一种类型,而null是[特殊]值。

这应该有助于解释它。 Swift - Optional Void

相关问题