参见英文答案 How to create local scopes in Swift?5个 在具有块级范围的语言中,我有时会创建任意块,这样我就可以封装局部变量,而不会让它们污染其父级的范围: func myFunc() { // if statements ge
在具有块级范围的语言中,我有时会创建任意块,这样我就可以封装局部变量,而不会让它们污染其父级的范围:
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
