0

Google's protobuf3 generates structs where an optional of type T is represented as a pair

  • .xyz: T which returns T's default value if xyz is not available
  • .hasXyz: Bool which tells whether the xyz is actually set

This then leads to a need to unpack this tuple back to a single optional, ex. like this:

let xyz: T? = {
  if protobufObj.hasXyz {
    return protobufObj.xyz
  }
  return nil
}()

The same goes for writing:

if let xyz = maybeXyz {
  protobufObj.xyz = xyz
} else {
  protobufObj.clearXyz()
}

Can this code be automated/templated somehow for all the properties without doing the above boilerplate code for each property? I C++ I'd use macro, but Swift doesn't have macros.

(Here is a relevant protobuf issue about why they don't expose the optional because of backwards compatibility.)

Tomáš Kafka
  • 4,405
  • 6
  • 39
  • 52

0 Answers0