简体   繁体   English

在Swift中返回没有返回值的函数

[英]Return in function without return value in Swift

Let's take a look at this function:我们来看看这个函数:

func nothing(){
    return
}

it does not return a value, but we can write return statement how Swift handle that ?它不返回值,但我们可以编写return语句 Swift 如何处理它? what happens behind the scene does return without value returns 0 or any value to handle this case ?幕后发生的事情确实return而没有值返回 0 或任何值来处理这种情况?

The following signatures all return an instance of the empty tuple () (typealiased as Void ).以下签名都返回空元组()实例(类型别名为Void )。

func implicitlyReturnEmptyTuple() { }

func explicitlyReturnEmptyTuple() {
    return ()
}

func explicitlyReturnEmptyTupleAlt() {
    return
}

In all of the three above, the return type of the function, in the function signature, has been omitted, in which case it is implicitly set to the empty tuple type, () .在上述所有三个中,函数签名中函数的返回类型已被省略,在这种情况下,它被隐式设置为空元组类型() Ie, the following are analogous to the three above即,以下与以上三个类似

func implicitlyReturnEmptyTuple() -> () { }

func explicitlyReturnEmptyTuple() -> () {
    return ()
}

func explicitlyReturnEmptyTupleAlt() -> () {
    return
}

With regard to your comment below (regarding body of implicitlyReturnEmptyTuple() where we don't explicitly return () );关于您在下面的评论(关于我们没有明确返回()implicitlyReturnEmptyTuple()式返回implicitlyReturnEmptyTuple()主体); from the Language Guide - Functions: Functions without return values :来自语言指南 - 函数:没有返回值的函数

Functions are not required to define a return type.函数不需要定义返回类型。 Here's a version of the sayHello(_:) function, called sayGoodbye(_:) , which prints its own String value rather than returning it:这是sayHello(_:)函数的一个版本,称为sayGoodbye(_:) ,它打印自己的String值而不是返回它:

 func sayGoodbye(personName: String) { print("Goodbye, \\(personName)!") }

... ...

Note注意

Strictly speaking, the sayGoodbye(_:) function does still return a value , even though no return value is defined.严格来说, sayGoodbye(_:)函数仍然返回一个 value ,即使没有定义返回值。 Functions without a defined return type return a special value of type Void .没有定义返回类型的函数返回一个Void类型的特殊值 This is simply an empty tuple, in effect a tuple with zero elements, which can be written as () .这只是一个空元组,实际上是一个元素为零的元组,可以写成()

Hence, we may omit return ... only for () -return ( Void -return) function, in which case a () instance will be returned implicitly.因此,我们可以省略return ...仅用于() -return ( Void -return) 函数,在这种情况下,将隐式返回()实例

在这种情况下, return仅意味着“离开函数”。

Functions are first class objects in Swift .函数是 Swift 中的第一类对象。 They have a type他们有一个类型

func nothing(){
    return
}

Actual representation of the above function is like this上述函数的实际表现是这样的

func nothing()->(){
        return
    }

In the above code the type of the function is an empty tuple在上面的代码中,函数的类型是一个空元组

"()" “()”

If you assign the above function to some variable , we can see the returned tuple如果将上述函数分配给某个变量,我们可以看到返回的元组

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM