简体   繁体   English

快速与“ return”的功能混淆

[英]confused with the functionality of `return` in swift

I am confused with return in Swift. 我对Swift的return感到困惑。 I understand it's used to return the value in a function, if used like this: 我了解它用于在函数中返回值,如果使用时是这样的:

func double(value: int) -> Int { 
    return value * 2
}

But I often just see return being used, like in a guard statement in an optional binding like this: 但是我经常看到return被使用,就像在一个可选的绑定中的guard声明中一样:

guard let value = value else (
    print ("nothing")
    return
}

So what is the purpose of having just return in the guard statement like this? 那么,只returnguard声明的目的是什么? Actually, I often see this not only in guard statements when unwrapping optional values. 实际上,解包可选值时,我不仅在guard声明中经常看到这种情况。 I always find this problem when writing code, when I want to use an optional string from a dictionary. 当我想使用字典中的可选字符串时,我总是在编写代码时发现此问题。

let info = ["name": "sarah", "hometown": "sydney"]

class UserInfo {

    func getTheName() -> String {
        guard let name = info["name"] else { return }

        return name
    }
}
// Compile time error: "Non-void function should return a value"

I get this error even though I have written return name . 即使我写了return name我也会收到此错误。 Xcode still complains that I have not returned a value. Xcode仍然抱怨我还没有返回值。 Is it because of the return in the guard statement? 是因为guard声明中的return

So, could you please tell me the purpose of return in Swift? 那么,能否请您告诉我Swift return的目的? It is confusing for me. 这让我感到困惑。

return without any argument returns Void . 不带任何参数的return返回Void This form of the return statement can only be used with a function that returns Void . 这种形式的return语句只能与返回Void的函数一起使用。

Once the return statement executes, the function exits and no more code in your function executes. 一旦执行return语句,该函数将退出,并且该函数中的其他代码将不再执行。 Since you have a return in the guard statement, the second return name won't be executed (it couldn't anyway since it wouldn't have a name to return), which is why you get a compiler error; 由于在guard语句中有一个return ,因此第二个return name将不会执行(因为它没有要return name将无法执行),这就是为什么会出现编译器错误; the compiler looks at all of the paths that your function could take to return something and ensures that all of those paths return what the function signature says it will. 编译器会查看函数可以返回所有内容的所有路径,并确保所有这些路径都返回函数签名说明的内容。

The function in your question states that it returns a String , so you can't simply say return in the guard statement as that returns Void , violating the contract expressed by your function signature. 您问题中的函数声明它返回String ,因此您不能简单地在guard语句中说return ,因为它返回Void ,违反了函数签名所表示的约定。

You could return a default value that isn't Void : 您可以返回不是Void的默认值:

func getTheName () -> String {
    guard let name = info["name"] else {
        return ""
    }
    return name
}    

This could be written much more succinctly using the nil-coalescing operator ; 这可以使用nil-coalescing运算符更简洁地编写; return info["name"] ?? ""

You can also use return in a function that returns Void (or has no explicit return type, in which case it is implicitly understood to return Void ) 您还可以在返回Void的函数中使用return (或没有显式的返回类型,在这种情况下,将其隐式理解为返回Void

So you could have a function like: 因此,您可以使用以下功能:

func maybePrint(theMessage: String?) -> Void {
    guard let msg = theMessage else {
        return
    }
    print(msg)
}

You're on the right track. 您走在正确的轨道上。

In your guard statement inside getTheName(), the 'return' keyword will try to exit the function itself if the guard fails. 在getTheName()内的保护声明中,如果保护失败,则“ return”关键字将尝试退出函数本身。 But the function requires you to return a String and as such you get the compiler error. 但是该函数要求您返回一个String,因此会出现编译器错误。

Here is a portion of another SO answer to a similar question: 这是类似问题的另一个SO答案的一部分:

guard forces you to exit the scope using a control transfer statement. 保护会强制您使用控制转移语句退出作用域。 There are 4 available to you: 有4种可供您选择:

return and throw both exit the function/method continue can be used within loops (while/for/repeat-while) break can be used in loops (while/for/repeat-while) to exit the immediate scope. return和throw都退出函数/方法continue可以在循环中使用(while / for / repeat-while)break可以在循环中使用(while / for / repeat-while)以退出立即作用域。 Specifying a label to break to will allow you to exit multiple scopes at once (eg breaking out of nested loop structure). 指定要中断的标签将使您可以立即退出多个作用域(例如中断嵌套循环结构)。 When using a label, break can also be used in if scopes. 使用标签时,在if范围内也可以使用break。 Additionally, you may exit the scope by calling a function that returns Never, such as fatalError. 此外,您可以通过调用返回Never的函数(例如fatalError)退出范围。

Stack Overflow: If the Swift 'guard' statement must exit scope, what is the definition of scope? 堆栈溢出:如果Swift'guard'语句必须退出范围,那么范围的定义是什么?

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

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