Dropping Curly Braces From Single Statement `guard ... else` Blocks

As no one seems too enthused by the idea, as an alternative, may I propose we instead add fixits to the language to automatically add braces?

ie., instead of seeing the following:

guard
    credentialDescriptor.type == .publicKey,
    let id = CredentialSource.ID(bytes: credentialDescriptor.id)
else return nil // Error: Expected '{' after 'guard' else

It could instead read:

guard
    credentialDescriptor.type == .publicKey,
    let id = CredentialSource.ID(bytes: credentialDescriptor.id)
else return nil // Error: return statement in 'guard ... else' must be
                //         enclosed in '{}` braces. Add them?

After fix it:

guard
    credentialDescriptor.type == .publicKey,
    let id = CredentialSource.ID(bytes: credentialDescriptor.id)
else { return nil }

Another few examples, brought to you by code I literally just wrote and was interupted by the compiler to fix:

guard credentialOptions.isEmpty
else throw WebAuthnError.noCredentialsAvailable // Error: throw statement
        // in 'guard ... else' must be enclosed in '{}` braces. Add them?

guard bytes.count >= uuidSize else return nil // Error: return statement
        // in 'guard ... else' must be enclosed in '{}` braces. Add them?
guard credentialOptions.isEmpty
else { throw WebAuthnError.noCredentialsAvailable }

guard bytes.count >= uuidSize else { return nil }
15 Likes

Yeah, improved diagnostics with more fix-its are always welcome.

2 Likes

Sure, you can make diagnostic improvements such as this without a proposal on Swift Evolution!

The existing error message seems fine as-is; a fix-it that adds both the beginning and end braces when the enclosed statement includes an unconditional return seems pretty sensible and a straightforward improvement.

3 Likes

A fix-it would be cool.

2 Likes