Jump out of function recursive function

I wrote a parser in Objective-C about a very ambiguous language . Everything works fine. I often jump out of many function calls by throwing an exception (I continue to be in my code, so the exception will never exit the parser).

I was thinking about porting the code to Swift, then I noticed that there is no exception handling in Swift.

I don't need exception handling, and I don't need it , but an upstart from many different nested functions was called when using parser writing .

Is there a good way instead of passing exceptions to a block @catch

in Swift?


An example of a recursive function to make it clearer (playground working code):

import Foundation

func addToSum(sum: Int, rest: String) -> Int {
    if rest == "" {
        return sum
    } else {
        if rest[rest.endIndex.predecessor()] != "i" {
            // can't throw exception, if scratches is like "iiiiiiiiiiiioiiiiii"
        }

        var shorterRest = rest.substringToIndex(rest.endIndex.predecessor())
        return addToSum(sum + 1, shorterRest)
    }
}

let scratches = "iiiiiiiiiiiiiiiiiiiii"
var sum = addToSum(0, scratches) // sum is 11 ;-)

      

I know the example is not that good because it is only one function and you can easily add an error, but then I had to go through each function call.

See a larger picture. I don't need any reverse processing in the parser.


Here is a link that has the same problem: use exceptions as flow control in parsers. Unfortunately, he doesn't answer.

+3


source to share


1 answer


In this case, it is fairly easy to handle by returning an option. Instead of throwing an exception, just return nil

and let it propagate the chain fallback.



func addToSum(sum: Int, rest: String) -> Int? {
    if rest == "" {
        return sum
    } else {
        if rest[rest.endIndex.predecessor()] != "i" {
            return nil
        }

        var shorterRest = rest.substringToIndex(rest.endIndex.predecessor())
        return addToSum(sum + 1, shorterRest)
    }
}

let scratches = "iiiiiiiiiiiiiiiiiiiii"
var sum = addToSum(0, scratches)  // sum is 21, actually
sum = addToSum(0, "iiiioiii")     // sum is now nil

      

+3


source







All Articles