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

标签 swift closures conditional-binding

我在这里是第一次接触 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/

相关文章:

swift - 我们如何使用 Assets 目录颜色集?

javascript - 意外行为 : Javascript, setTimeout() 和 IIFE

javascript - js 中的闭包如何与 let 一起工作?

javascript - 在循环中使用相同的变量来解决 "Closures in the loop"问题

ios - ScrollView 内的 TextView 粘在键盘上

ios - 是否可以将 ViewController 分配给 SwiftUI View ?

ios - iOS应用程序的结构

c# - 仅当属性不为 null 时才进行条件依赖注入(inject)绑定(bind)

protocols - 条件绑定(bind)中的绑定(bind)值必须是可选类型