gpt4 book ai didi

swift - 理解没有返回类型的闭包语法

转载 作者:搜寻专家 更新时间:2023-10-31 22:12:26 25 4
gpt4 key购买 nike

我在这里是第一次接触 swift,我偶然发现了一个闭包语句,根据我目前对闭包的编写方式的理解,它对我来说没有多大意义。这实际上是一个由两部分组成的问题,因为我也不太了解这个闭包的条件绑定(bind)背后的意图/解释。

我抛出的代码块是这样的:

 FIRAuth.auth()?.createUser(withEmail: email, password: password) {
(user, error) in if let error = error {
print(error.localizedDescription)
return
}
}

我的理解是,闭包需要根据文档定义指定一个返回类型 (something1, something2) -> () 所以从上面的代码来看,这是否意味着 swift可以通过不包含 -> () 来推断 void 返回吗?

我的假设是条件绑定(bind)语句只是说'如果将错误参数传递到此闭包中,则打印错误?

请在您的解释中尽可能详细,以便我加深理解。干杯!

最佳答案

以下都是等价的

func foo1() -> () { }
func foo2() -> () { return () }
func foo3() -> () { return Void() }
func foo4() -> () { return }

func foo5() -> Void { }
func foo6() -> Void { return () }
func foo7() -> Void { return Void() }
func foo8() -> Void { return }

func foo9() { }
func foo10() { return () }
func foo11() { return Void() }
func foo12() { return }

print(type(of: foo1)) // (()) -> ()
// ...
print(type(of: foo5)) // (()) -> ()
// ...
print(type(of: foo9)) // (()) -> ()
// ...

如果没有返回 type 提供给函数(/closure),那么空元组 type (由 Void 类型别名)被推断。但是,我们可以显式提供此返回类型,可以是()(类型),也可以是Void .来自 the language guide - functions :

Functions Without Return Values

Functions are not required to define a return type. ...

...

Strictly speaking, this version of the greet(person:) function does still return a value, even though no return value is defined. Functions without a defined return type return a special value of type Void. This is simply an empty tuple, which is written as ().

反之,如果在函数 block 的末尾没有给出return,则相当于显式返回一个空元组的实例,即()()。这也可以简单地写成 return

关于swift - 理解没有返回类型的闭包语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41412032/

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