如何在 Swift 中创建本地作用域? [英] How to create local scopes in Swift?

查看:36
本文介绍了如何在 Swift 中创建本地作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在 Objective-C 中使用局部作用域来使命名更清晰.

I'm regularly using local scopes in Objective-C to make naming clearer.

{
    UILabel *label = [[UILabel alloc] init];
    [self addSubview:label];
    self.titleLabel = label;
}

我正在尝试像这样在 Swift 中重写这段代码:

I am trying to rewrite this code in Swift like this:

{
    let label = UILabel()
    self.addSubview(label)
    self.titleLabel = label
}

这给了我以下错误:

错误:带括号的语句块是一个未使用的闭包.

那么如何在 Swift 中创建本地作用域?

So how can I create a local scope in Swift?

推荐答案

更新: 在 Swift 2.0 中,您只需使用 do 关键字:

Update: In Swift 2.0, you just use the do keyword:

do {
    let label = UILabel()
    self.addSubview(label)
    self.titleLabel = label
}

<小时>

这适用于 Swift 2.0 之前的版本:

您可以定义类似的内容:

You can define something similar to this:

func locally(@noescape work: () -> ()) {
    work()
}

然后使用这样一个locally块如下:

And then use such a locally block as follows:

locally {
    let g = 42
    println(g)
}

(灵感来自 Scala 的 local="noreferrer">预定义 对象.)

(Inspired by locally in Scala's Predef object.)

这篇关于如何在 Swift 中创建本地作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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