Direct return in nested functions

Hi. When I write code I usually structure my functions like this:

func ex () -> Either<Int, String> {
   var i = Int.random(in: 0 ... 10)
   func skip () {
      i += 1
      //if i > 8 {  return! .right("special") }
      //return as if this was the parent function execution scope
   return .right(double())

Writing logic in this style have benefits because local state of the function is managed implicitly and code is cleaner. I was recently writing a parser and found this kind of code easier to understand.
I can define it using throwing or set skip to return optional value, but I find these options suboptimal.

Any advice you can give about code like this?

Swift is pretty dead set on making control flow explicit.

In this case, I think the best you can do is make your functions throwing, and throw from the nested function.

Terms of Service

Privacy Policy

Cookie Policy