belay icon indicating copy to clipboard operation
belay copied to clipboard

Swift-like guard statement

Open ngsilverman opened this issue 5 years ago • 0 comments

A few people have been comparing parts of Belay to the Swift guard statement so I looked to see if there was any inspiration to be found there.

Here in its own basic form:

guard condition else {
    // statements
    // exit
}

It is very similar to:

expect.isTrue(condition) {
    // statements
    // exit
}

Belay also provides a variant that is very useful when a false condition can be handled without exiting from the parent:

expect(condition) {
    // statements
    // does not need to exit
}

And of course if one doesn't need to handle expectations globally it's just as easy to write:

if (!condition) {
    // …
}

The Swift guard also supports an "optional binding declaration":

guard let constantName = someOptional else {
    // …
}

Which is very similar to:

val constantName = expect.isNotNull(someOptional) {
    // …
}

One major difference: Swift support multiple bindings, Belay does not in this case.

And another: the variables assigned a value from an optional binding can be used as part of the condition:

guard let constantName = someOptional, condition(constantName) else {
    // …
}

ngsilverman avatar Dec 09 '20 13:12 ngsilverman