0

I know that Swift does not have try/catch, but are there any other methods by which I can exit from a function to one higher up on the stack without returning to the intervening functions? For example, in the following code is it possible to exit from d() directly back to a() so that only the first print statement (in a()) is executed?

func a() {
    b()
    println("returned to a()")
}
func b() {
    c()
    println("returned to b()")
}
func c() {
    d()
    println("returned to d()")
}
func d() {
    // exit to a()
}

a()

If Swift did have try/catch I could simply wrap the call to b() with try and throw an exception in d().

Community
  • 1
  • 1
nathan
  • 5,466
  • 3
  • 27
  • 24
  • this is X/Y problem. what is your original question? if you just want "is it possible", I guess the correct answer at the moment is NO. – Bryan Chen Jun 08 '14 at 11:51
  • I really do want "is it possible"--I was hoping someone cleverer than me might have figured out a way to do this. There are a lot of use cases for it and it's a clean way to do things, but I know what the alternatives are and how to use them. – nathan Jun 08 '14 at 18:41
  • It is not supported because there are not enough valid use cases to support it. So there are most likely better alternatives available and people don't need such feature. So again, it is not possible, and not really useful. – Bryan Chen Jun 09 '14 at 08:52

2 Answers2

1

One would expect more advanced control constructs, such as call-with-current-continuation or lessor related, to appear once exceptions are introduced into the language. For now, nothing.

GoZoner
  • 67,920
  • 20
  • 95
  • 145
0

No, Swift does not have this in the core language. There may be hacks to work around it (manipulate the stack manually, etc) but the best way to solve this is to just return some value that indicates its exit status, and always check the result of function calls. Like in C.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105