Bre*_*aut 4 scope swift swift2
在具有块级范围的语言中,我有时会创建任意块,这样我就可以封装局部变量,而不会让它们污染其父级的范围:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
当我在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)
})()
}
Run Code Online (Sandbox Code Playgroud)
在Swift中是否支持这样的东西?
您可以使用do
语句在Swift中创建任意范围.例如:
func foo() {
let x = 5
do {
let x = 10
print(x)
}
}
foo() // prints "10"
Run Code Online (Sandbox Code Playgroud)
按照雨燕编程语言:
do语句用于引入新范围,并且可以选择包含一个或多个catch子句,其中包含与定义的错误条件匹配的模式.在do语句范围内声明的变量和常量只能在该范围内访问.
Swift中的do语句类似于
{}
C中用于分隔代码块的花括号(),并且在运行时不会产生性能成本.参考:Swift编程语言 - 语言指南 - 语句 - 做声明