swift允许没有条件/循环的代码块减小局部变量范围吗? [英] Does swift allow code blocks without conditions/loops to reduce local variable scope?

查看:73
本文介绍了swift允许没有条件/循环的代码块减小局部变量范围吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有块级作用域的语言中,有时我会创建任意块,只是为了封装局部变量而不让它们污染其父级作用域:

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)
  }
}

当我在Swift中执行此操作时,它认为我正在创建一个闭包,并且不执行代码.我可以将其创建为一个闭包并立即执行,但这似乎会带来执行开销(不仅仅为了代码清洁而值得).

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)
  })()
}

在Swift中是否支持这样的事情?

Is there support for something like this in Swift?

推荐答案

您可以使用do语句在Swift中创建任意范围.例如:

You can use a do statement to create arbitrary scope in Swift. For example:

func foo() {
    let x = 5

    do {
        let x = 10
        print(x)
    }
}

foo() // prints "10"

按照 Swift编程语言 :

do语句用于引入新作用域,并且可以选择 包含一个或多个catch子句,其中包含匹配的模式 针对定义的错误条件.在中声明的变量和常量 do语句的范围只能在该范围内访问.

The do statement is used to introduce a new scope and can optionally contain one or more catch clauses, which contain patterns that match against defined error conditions. Variables and constants declared in the scope of a do statement can be accessed only within that scope.

Swift中的do语句类似于C中的花括号({}) 分隔代码块,并且不会产生性能损失 运行时.

A do statement in Swift is similar to curly braces ({}) in C used to delimit a code block, and does not incur a performance cost at runtime.

参考: Swift编程语言-语言指南-语句-做语句

这篇关于swift允许没有条件/循环的代码块减小局部变量范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆