gpt4 book ai didi

swift - 关闭 Void -> Void

转载 作者:行者123 更新时间:2023-11-28 11:11:35 24 4
gpt4 key购买 nike

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

你能告诉我为什么以下不打印“Example”吗?它只是打印“()
正如您在评论中看到的,它在 7.1 中有效。

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

printThis({ print("Example") })

最佳答案

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

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 '()'

() value 与您的 ()->() 闭包无关,但与 printThis(..) 是一个空函数,因为它隐式返回 () 类型的值 ()(空元组)。

作为示例,请考虑以下情况,其副作用是将 “Example” 打印到控制台,但整数 value 为 1。

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

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

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


最后,关于“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: ()? */

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

关于swift - 关闭 Void -> Void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com