局部Scope 代码块

隔离代码有效范围

Posted by Genie on April 17, 2021

OC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-(void)loadView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    {
        UILabel *titleLabel = [[UILabel alloc]
                initWithFrame:CGRectMake(150, 30, 20, 40)];
        titleLabel.textColor = [UIColor redColor];
        titleLabel.text = @"Title";
        [view addSubview:titleLabel];
    }

    {
        UILabel *textLabel = [[UILabel alloc]
                initWithFrame:CGRectMake(150, 80, 20, 40)];
        textLabel.textColor = [UIColor redColor];
        textLabel.text = @"Text";
        [view addSubview:textLabel];
    }

    self.view = view;
}

GNU C

1
2
3
4
5
6
7
8
self.titleLabel = ({
    UILabel *label = [[UILabel alloc]
            initWithFrame:CGRectMake(150, 30, 20, 40)];
    label.textColor = [UIColor redColor];
    label.text = @"Title";
    [view addSubview:label];
    label;
});

swift

通过尾随闭包实现

1
2
3
func local(closure: ()->()) {
    closure()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
override func loadView() {
    let view = UIView(frame: CGRectMake(0, 0, 320, 480))

    local {
        let titleLabel = UILabel(frame: CGRectMake(150, 30, 20, 40))
        titleLabel.textColor = UIColor.redColor()
        titleLabel.text = "Title"
        view.addSubview(titleLabel)
    }

    local {
        let textLabel = UILabel(frame: CGRectMake(150, 80, 20, 40))
        textLabel.textColor = UIColor.redColor()
        textLabel.text = "Text"
        view.addSubview(textLabel)
    }

    self.view = view
}

匿名闭包

1
2
3
4
5
6
7
titleLabel = {
    let label = UILabel(frame: CGRectMake(150, 30, 20, 40))
    label.textColor = UIColor.redColor()
    label.text = "Title"
    self.view.addSubview(label)
    return label
}()

通过scope 来隔离代码,你会发现在手写UI的时候,可以定义少的变量名称,我们可以重复使用