如何使用Swift从内部函数退出函数作用域? [英] How to exit a function scope from inner function using Swift?

查看:47
本文介绍了如何使用Swift从内部函数退出函数作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 return 可以退出当前函数的范围,但是也可以退出正在调用内部函数的外部函数的范围吗?

With return it is possible to exit the scope of the current function but is it also possible to exit the scope of the outer function that is calling the inner function?

func innerFunction() {
  guard 1 == 2 else {
    // exit scope of innerFunction and outerFunction
  }
}

func outerFunction() {
  innerFunction()
  print("should be unreachable")
}

有一种方法可以使用我们可以检查的内部函数的返回值:

There could be one approach using a return value of the inner function that we can check for:

func innerFunction() -> Bool {
  guard 1 == 2 else {
    return false
  }
  return true
}

func outerFunction() {
  guard innerFunction() else {
    return
  }
  print("should be unreachable")
}

这种方法的问题在于,如果功能变得更加复杂,并且您不得不一遍又一遍地使用它们,它会很快使您的代码混乱.

The problem with this approach is that it can clutter your code pretty quickly if the functions become more complicated and you have to use them over and over again.

考虑将这种方法与 XCTest 一起使用.看起来像这样:

Consider applying this approach with XCTest. It would look like this:

func testFoobar() {
  guard let unwrappedObject = helperFunction() else {
    XCTFail("A failure message that can change with each helperFunction call")
    return
  }
  print("should be unreachable when helperFunction already failed")
}

我想要类似的东西:

func testFoobar() {
  let unwrappedObject = helperFunction()
  print("should be unreachable when helperFunction already failed")
}

推荐答案

这基本上是Swift的错误处理功能:

This is basically what Swift's error handling does:

func outer() throws
{
    try inner()
    print("Unreachable")
}

struct DoNotContinue : Error {}

func inner() throws
{
    throw DoNotContinue()
}

do { try outer() }
catch _ { print("Skipped the unreachable") }

当然,请注意,调用方仍然对此有控制权:它可以捕获引发的错误本身,而不仅仅是退出.

Note, of course, that the caller still has control over this: it could catch the thrown error itself instead of just exiting.

这种方法的问题是它可能使您的代码混乱

problem with this approach is that it can clutter your code

允许被叫方直接退出其呼叫者还有一个更为严重的问题,那就是控制流非常很快变得难以理解.想象一下,您有两层.阅读顶层功能后,您将不知道会发生什么.您必须自己递归到每个被调用方的被调用方,以确保原始代码将继续进行下去.

There's a much more serious problem with allowing callees to directly exit their callers, and that is that the flow of control very quickly becomes incomprehensible. Imagine that you have a couple of layers of this. Reading the top-level function, you no longer have any clear idea what can happen. You must yourself recurse into every callee's callee to make sure that the original code will continue on its course.

这篇关于如何使用Swift从内部函数退出函数作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆