Erik Westwig
Erik Westwig

Reputation: 744

Does swift have the equivalent of a "with block"

In several Microsoft languages, there is the idea of a "with block". For example, instead of

myObject.x = 5
myObject.y = 10
myObject.z = 12

you can write something like

With myObject
    .x = 5
    .y = 10
    .z = 12
End With

Is there something similar in Swift?

Upvotes: 2

Views: 128

Answers (1)

JAL
JAL

Reputation: 42449

Not built into the language, but there is a library called Then which provides this functionality:

let myObject = MyObject().then {
    $0.x = 5
    $0.y = 10
    $0.z = 12
}

If you want this behavior on instantiation without a dependency, you can use a var that is returned from a closure:

let myObject: MyObject = {
    let _myObject = MyObject()
    _myObject.x = 5
    _myObject.y = 10
    _myObject.z = 12
    return _myObject
}()

Upvotes: 3

Related Questions