Guards are a powerful part of the Swift language, but they come with a cognitive cost β they break the continuity of a run of statements. For a multiple expression guard
, this is perfectly acceptable, because the guard itself looks and acts like its own block of related code. But if you are using a guard
to simply unwrap an optional, it leads to an unfortunate break in the flow of the code.
Take this example:
guard let store = sharedNotesStore else { throw Error.noSharedNotesStoreAvailable }
let blobs: [SharedNote.Blob] = [.init("ABC")]
guard let data = section.propertyDictionary.json else { throw Error.serializationFailure }
let key = UUID().uuidString
guard let section = section(withIdentifier: noteIdentifier, data: data) else { throw Error.noSectionFoundForNote }
let sharedNote = SharedNote(store: store, section: section, key: key, blobs: blobs)
This code just converts data from one type to the next. It is very common in the real world. But as it is, it is not so easy to read. Although most of the lines amount to a let
declaration, the error handling, in the form of the guard
's, reduces the readability. There is no left alignment of let
keywords β the guard
's jump in β making a quick scan of the code tricky.
What if the guard
keyword could be left out in cases where you have a simple, single guard-let-else
combination? In effect, the option of using a let-else
, which behaves the same way, but which is syntactically more similar to a standard let
.
With this approach, the code above would look like this.
let store = sharedNotesStore else { throw Error.noSharedNotesStoreAvailable }
let blobs: [SharedNote.Blob] = [.init("ABC")]
let data = section.propertyDictionary.json else { throw Error.serializationFailure }
let key = UUID().uuidString
let section = section(withIdentifier: noteIdentifier, data: data) else { throw Error.noSectionFoundForNote }
let sharedNote = SharedNote(store: store, section: section, key: key, blobs: blobs)
IMO this is much more readable. It's a small change, but this type of code pervades real world software projects, and this small change would make a lot of swift code that much more readable.