Skip to content

Swift-like guard statement #4

@ngsilverman

Description

@ngsilverman

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 {
    // …
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions