关闭空隙 - >空虚

时间:2016-01-09 10:52:20

标签: swift swift2

在Xcode 7.2(7C68)Playground中运行以下命令。 OS X 10.10.5

你能告诉我为什么以下不打印"示例"?它只是打印" ()"
正如你在评论中看到的那样,它可以在7.1中使用。

func printThis(xprint : Void -> Void) {
    xprint()
}

printThis({ print("Example") })

1 个答案:

答案 0 :(得分:3)

确保控制台中的输出与表达式值不同。另请注意,Void只是空元组()的类型。默认情况下,没有返回类型的函数返回空元组的{em>值()

func printThis(xprint : Void -> Void) {
    xprint()
}

let a = printThis({ print("Example") })
/* the _value_ of this expression is ()
   the side effect of this expression is that "Example" is
   printed to the console output */
print(a) // prints '()'

() 与您的()->()闭包无关,但事实上printThis(..)是一个无效函数,从某种意义上说隐式返回类型()的值()(空元组)。

作为示例,请考虑以下情况,并将“示例”打印到控制台,但整数为1。

func printThat(xprint : Void -> Void) -> Int {
    xprint()
    return 1
}

let b = printThat({ print("Example") }) // side effect: prints "Example"
print(b) // 1

您在游乐场右侧看到的是变量和表达式的。请参阅底部以查看控制台输出

最后,关于“void”函数,请注意这两个函数签名之间没有区别:

func myFunc(myVar: String)        // implicitly returns _value_ '()' of _type_ ()
func myFunc(myVar: String) -> ()

奇怪的是,你可以有一个可选的空元组类型,所以下面的函数与上面的两个不同:

func myFunc(myVar: String) -> ()? {
    print(myVar)
    return nil
}

var c = myFunc("Hello") /* side effect: prints 'Hello'
                           value: nil
                           type of c: ()?              */

有关空元组()的类型和值的详细信息,请参阅例如。