"Finally" equivalent for Swift?

493 views Asked by At

https://nearthespeedoflight.com/browser.html

    func untilThrowOrEndOfTokensReached<ConsumedType>(perform: () throws -> ConsumedType) -> [ConsumedType] {

    var results = [ConsumedType]()

    do {
        while isNotAtEnd {
            results.append(try perform())
        }
    } catch {
        return results
    }
    return results
}

Double return results looks strange and I want to fix it.

There is a similar question:

What's the equivalent of finally in Swift

It is recommended to use defer but this code won't work:

func untilThrowOrEndOfTokensReached<ConsumedType>(perform: () throws -> ConsumedType) -> [ConsumedType] {
    
    var results = [ConsumedType]()
    defer {
        return results
    }
    do {
        while isNotAtEnd {
            results.append(try perform())
        }
    } catch {
    }
}

'return' cannot transfer control out of a defer statement

How to resolve this issue? Or should I just remove return results inside catch block?

1

There are 1 answers

1
Alexander On

You don't need a defer here at all. I think what you're looking for is:

func untilThrowOrEndOfTokensReached<ConsumedType>(perform: () throws -> ConsumedType) -> [ConsumedType] {
    var results = [ConsumedType]()

    do {
        while isNotAtEnd {
            results.append(try perform())
        }
    } catch {
        // Log the error or whatever
    }

    return results
}

This will return the results accumulate so far, as soon as the first perform() call raises.