微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift是否允许没有条件/循环的代码块来减少局部变量范围?

参见英文答案 > How to create local scopes in Swift?                                    5个
在具有块级范围的语言中,我有时会创建任意块,这样我就可以封装局部变量,而不会让它们污染其父级的范围:

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中执行此操作时,它认为我正在创建一个闭包并且不执行代码.我可以创建它作为一个闭包并立即执行,但这似乎会带来执行开销(不值得为代码清洁).

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中是否支持这样的东西?

解决方法

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

func foo() {
    let x = 5

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

foo() // prints "10"

按照The Swift Programming Language

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.

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.

Ref: The Swift Programming Language – Language Guide – Statements – Do Statement

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐