In languages with block level scope, I sometimes create arbitrary blocks just so I can encapsulate local variables and not have them pollute their parents' scope:
func myFunc() {
// if statements get block level scope
if self.someCondition {
var thisVarShouldntExistElsewhere = true
self.doSomethingElse(thisVarShouldntExistElsewhere)
}
// many languages allow blocks without conditions/loops/etc
{
var thisVarShouldntExistElsewhere = false
self.doSomething(thisVarShouldntExistElsewhere)
}
}
When I do this in Swift, it thinks I'm creating a closure and doesn't execute the code. I could create it as a closure and immediately execute, but that seems like it would come with execution overhead (not worth it just for code cleanliness).
func myFunc() {
// if statements get block level scope
if self.someCondition {
var thisVarShouldntExistElsewhere = true
self.doSomethingElse(thisVarShouldntExistElsewhere)
}
// converted to closure
({
var thisVarShouldntExistElsewhere = false
self.doSomething(thisVarShouldntExistElsewhere)
})()
}
Is there support for something like this in Swift?