用于对象的可链式操作的语法糖
它提供了一些以函数式方式创建和操作对象的方法。
func
then(_ block: (inout Self) throws -> Void) rethrows -> Self
用于值类型。允许链式修改。
struct Obj {
var a: String
var b: Int
}
let o = Obj(a: "hola", b: 0)
let c = o.then {
$0.a = "adios"
}
func
then(_ block: (Self) throws -> Void) rethrows -> Self
与之前相同,但用于引用类型。对于就地初始化非常有用。
class VC: UIViewController {
lazy var button = UIButton().then {
$0.addTarget(self, action: #selector(action), for: .touchUpInside)
}
@IBAction
func action() {
…
}
}
func
do(_ block: (Self) throws -> Void) rethrows
允许对对象执行终止操作
Obj(a: "hola", b: 0).then { $0.b = 3 }.do(print)