Does swift allow code blocks without conditions/loops to reduce local variable scope? -


this question has answer here:

in languages block level scope, create arbitrary blocks can encapsulate local variables , not have them pollute parents' scope:

func myfunc() {   // if statements 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 in swift, thinks i'm creating closure , doesn't execute code. create closure , execute, seems come execution overhead (not worth code cleanliness).

func myfunc() {   // if statements block level scope   if self.somecondition {     var thisvarshouldntexistelsewhere = true     self.dosomethingelse(thisvarshouldntexistelsewhere)   }    // converted closure   ({     var thisvarshouldntexistelsewhere = false     self.dosomething(thisvarshouldntexistelsewhere)   })() } 

is there support in swift?

you can use do statement create arbitrary scope in swift. example:

func foo() {     let x = 5      {         let x = 10         print(x)     } }  foo() // prints "10" 

as per the swift programming language:

the statement used introduce new scope , can optionally contain 1 or more catch clauses, contain patterns match against defined error conditions. variables , constants declared in scope of statement can accessed within scope.

a statement in swift similar curly braces ({}) in c used delimit code block, , not incur performance cost @ runtime.

ref: the swift programming language - language guide - statements - statement


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -