Skip to content

Protobuf OneOf Support

Compare
Choose a tag to compare
@christophhagen christophhagen released this 19 Jul 09:08
· 103 commits to master since this release
23d56cc

This version adds support for the protobuf Oneof feature.

A new protocol ProtobufOneOf signals that enums with associated values should be treated as a Oneof on the wire.

public protocol ProtobufOneOf { }

A protobuf definition of a oneof:

syntax = "proto3";
message ExampleOneOf {
   int32 field1 = 1;
   oneof alternatives {
       int64 id = 2;
       string name = 3;
   }
}

The corresponding Swift definition would be:

struct ExampleOneOf: Codable {

    let field1: Int32

    // The oneof field
    let alternatives: Alternatives
 
    // The OneOf definition
    enum Alternatives: Codable, ProtobufOneOf {
        case id(Int64)
        case name(String)
         
        // Field values, must not overlap with `ExampleOneOf.CodingKeys`
        enum CodingKeys: Int, CodingKey {
            case id = 2
            case name = 3
        }
    }
     
    enum CodingKeys: Int, CodingKey {
        case field1 = 1
        // The field id of the Oneof field is not used
        case alternatives = 123456
    }
 }

There are additional error cases added to signal errors during encoding and decoding:

For ProtobufEncodingError:

/**
 An unavailable encoding feature was accessed.

 The associated value contains a textual description of the unsupported access.
 */
case invalidAccess(String)

For ProtobufDecodingError:

/**
 A decoding feature was accessed which is not supported for protobuf encoding.

 The associated value contains a textual description of the invalid access.
 */
case invalidAccess(String)