Does swift allow code blocks without conditions/loops to reduce local variable scope? -
this question has answer here:
- how create local scopes in swift? 5 answers
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
Post a Comment