Like most languages, Swift supports variables of limited scope within conditionals, loops etc., however it doesn't seem to support a plain block on its own, which is a shame as I find it a very useful way to limit the scope of a variable, particularly costly ones that might be needed for the full length of a function.
For example, I might do something like (using Swift as an example, since this won't currently compile):
var results = []
while let newResult = someFunction() { results.append(newResult) }
{
var newItems = []
while let newItem = foobar() { newItems.append(newItem) }
// Process newItems into results so we can add them
results += newItems
}
// Do some more stuff down here
It can also be very handy for common placeholder names, but which may have different types at different parts in the execution. While I could declare different names, it can actually end up more confusing or messier than just reusing a good variable name with a clearly marked scope.
Of course I can do things like if true {}
to cheat a bit, but it seems unnecessary. So is there a way I can just declare a scope/block without having to put in a conditional?
I know it may have something to do with the way closures can be formed, but is there a way to do something like this purely to limit variable scope in Swift?