然后初始化

这在语法上类似于使用位置常量初始化的示例,但需要来自 https://github.com/devxoul/Then (附在下面) 的 Then 扩展。

let label = UILabel().then {
    $0.textAlignment = .Center
    $0.textColor = UIColor.blackColor(
    $0.text = "Hello, World!"
}

Then 扩展:

import Foundation

public protocol Then {}

extension Then 
{
    public func then(@noescape block: inout Self -> Void) -> Self {
        var copy = self
        block(&copy)
        return copy
    }
}

extension NSObject: Then {}