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?
You don't need a
deferhere at all. I think what you're looking for is:This will return the
resultsaccumulate so far, as soon as the firstperform()call raises.