Add option to generate proto3 optionals as swift optionals #1793
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
As discussed in #1114 the swift-protobuf generator does not generate swift optionals. Although I feel this makes complete sense from an wholistic view of an protobuf generator it does introduce tradeoffs mainly when using code generated for proto3.
Our main usage of swift-protobuf is done in combination with gRPC, which recommends using proto3 for describing the API.
Within our API Specifications we rely on marking fields as optional to be able to communicate to the client when to ignore/not handle specific fields because they are not present.
Not having generated swift optionals is not ideal since it's easy for an developer to forget checking the hazzer method that is generated which can cause bugs because the client than loses the information if the fields was never set and thus incorrectly interpreting the default value of an message as the "set" value.
As an example we have an message that includes an title and optional subtitle to display in the client
Mapping these to domain models in Swift requires checking the
has
functions that are generated:Not checking the
hasSubtitle
method would not result in an compiler error since accessingfoo.subtitle
will return de default (empty string) value, which could cause the client to allocate space to display an empty string instead of not allocating space at all. This issue becomes more apparent with larger and more complex models returned by the API.Thoughts behind the change
Proto3OptionalAsSwiftOptional
option that will enable generating swift optionals only for proto3 optionals.The deprecated
descriptor.hasOptionalKeyword
api had to be used to make sure swift optionals are only generated for messages explicitly marked asoptional
in the proto file.It would be great to know if this change is something that can be included here or if there are objections with introducing this option and we should look at other ways to achieve this.